symfonyroutestrailing-slash

Keep trailing slash in route with default parameter in Symfony 5.1


Symfony 5.1

I'm updating some legacy code and I need the following routes to match:
/article/ <--- matches default page 1 and has trailing slash
/article/2 <--- matches pages 2 through n with no trailing slash

If I use the route annotation...

* @Route("/article/{page}", name="article_show", requirements={"page"="\d+"})
* @param int $page
* @return Response
*/
public function show(int $page = 1) {

it redirects /article/ to /article removing the trailing slash. /article/2 works.

How do I keep the trailing slash when the page is 1?


Solution

  • According to https://symfony.com/doc/4.1/routing/optional_placeholders.html "Routes with optional parameters at the end will not match on requests with a trailing slash (i.e. /blog/ will not match, /blog will match)."

    So if you don't absolutely care about having a trailing slash, just add a defaults={"page"=1} . However if you really do... I don't see a better option than adding a second @Route with "/article/". Since your method has a default value for the parameter, it should work.