|
| 1 | +.. index:: |
| 2 | + single: Redirect URLs with a trailing slash |
| 3 | + |
| 4 | +Redirect URLs with a trailing slash |
| 5 | +=================================== |
| 6 | + |
| 7 | +The goal of this tutorial is to demonstrate how to redirect URLs with |
| 8 | +trailing slash to the same url without trailing slash |
| 9 | +(for example ``/en/blog/`` to ``/en/blog``). |
| 10 | + |
| 11 | +.. note:: |
| 12 | + |
| 13 | + For the moment, the :doc:`RoutingBundle <../bundles/routing/introduction>` |
| 14 | + can't achieve this automatically. |
| 15 | + |
| 16 | +You have to create a controller which will match any URL with a trailing |
| 17 | +slash, remove the trailing slash (keeping query parameters if any) and |
| 18 | +redirect to new URL with a 301 response status code:: |
| 19 | + |
| 20 | + // src/Acme/DemoBundle/Controller/RedirectingController.php |
| 21 | + namespace Acme\DemoBundle\Controller; |
| 22 | + |
| 23 | + use Symfony\Bundle\FrameworkBundle\Controller\Controller; |
| 24 | + use Symfony\Component\HttpFoundation\Request; |
| 25 | + |
| 26 | + class RedirectingController extends Controller |
| 27 | + { |
| 28 | + public function removeTrailingSlashAction(Request $request) |
| 29 | + { |
| 30 | + $pathInfo = $request->getPathInfo(); |
| 31 | + $requestUri = $request->getRequestUri(); |
| 32 | + |
| 33 | + $url = str_replace($pathInfo, rtrim($pathInfo, ' /'), $requestUri); |
| 34 | + |
| 35 | + return $this->redirect($url, 301); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | +And after that, register this controller to be executed whenever a url |
| 40 | +with a trailing slash is requested: |
| 41 | + |
| 42 | +.. configuration-block:: |
| 43 | + |
| 44 | + .. code-block:: yaml |
| 45 | +
|
| 46 | + remove_trailing_slash: |
| 47 | + path: /{url} |
| 48 | + defaults: { _controller: AcmeDemoBundle:Redirecting:removeTrailingSlash } |
| 49 | + requirements: |
| 50 | + url: .*/$ |
| 51 | + _method: GET |
| 52 | +
|
| 53 | +
|
| 54 | + .. code-block:: xml |
| 55 | +
|
| 56 | + <?xml version="1.0" encoding="UTF-8" ?> |
| 57 | + <routes xmlns="http://symfony.com/schema/routing"> |
| 58 | + <route id="remove_trailing_slash" path="/{url}"> |
| 59 | + <default key="_controller">AcmeDemoBundle:Redirecting:removeTrailingSlash</default> |
| 60 | + <requirement key="url">.*/$</requirement> |
| 61 | + <requirement key="_method">GET</requirement> |
| 62 | + </route> |
| 63 | + </routes> |
| 64 | +
|
| 65 | + .. code-block:: php |
| 66 | +
|
| 67 | + use Symfony\Component\Routing\RouteCollection; |
| 68 | + use Symfony\Component\Routing\Route; |
| 69 | +
|
| 70 | + $collection = new RouteCollection(); |
| 71 | + $collection->add('remove_trailing_slash', new Route('/{url}', array( |
| 72 | + '_controller' => 'AcmeDemoBundle:Redirecting:removeTrailingSlash', |
| 73 | + ), array( |
| 74 | + 'url' => '.*/$', |
| 75 | + '_method' => 'GET', |
| 76 | + ))); |
0 commit comments