Search code examples
phpsymfonyroutessymfony-3.3

Symfony redirect all routes ending with on url


Over my Symfony project let us suppose we have the following route:

$route= new Route('/my-method',array(
    '_controller'=>'AppBundle:MyController:myMethod'
));
$collection->add('my_method_route',$route);

$route= new Route('/my-method2',array(
    '_controller'=>'AppBundle:MyController:myAnotherMethod'
));
$collection->add('my_method2_route',$route);

$route= new Route('/anotherStuff',array(
    '_controller'=>'AppBundle:MyController:anotherStuff'
));
$collection->add('another_stuff',$route);

$route= new Route('/anotherStuff/{param}',array(
    '_controller'=>'AppBundle:MyController:anotherStuffOneParam'
));
$collection->add('another_stuff',$route);

$route= new Route('/anotherStuff/{param}/{another_param}',array(
    '_controller'=>'AppBundle:MyController:anotherStuffTwoParam'
));
$collection->add('another_stuff',$route);

And I want when a url ends with / eg. http//example.com/my-method/ to redirect into http//example.com/my-method.

So I was thinking if I can use regex as first parameter on route or to configure thew Symfony's routing system showhow in order to perform, the redirect.

But can Symfony accept a regex or somehow an optional part on url that it casn be ingored? eg to use '/my-method2/?' in order to tell that the route may end with / and just ignore theese stuff.


Solution

  • You want to redirect all url ending by a trailing slash to the same URL withouth right ?

    You'll have to create a route that match .*/$ then in the controller remove this "/".

    And there is a article that give the code on the symfony doc : https://symfony.com/doc/current/routing/redirect_trailing_slash.html