Skip to content

How to Allow a "/" Character in a Route Parameter

Warning: You are browsing the documentation for Symfony 2.x, which is no longer maintained.

Read the updated version of this page for Symfony 7.2 (the current stable version).

Sometimes, you need to compose URLs with parameters that can contain a slash /. For example, consider the /share/{token} route. If the token value contains a / character this route won't match. This is because Symfony uses this character as separator between route parts.

This article explains how you can modify a route definition so that placeholders can contain the / character too.

Configure the Route

By default, the Symfony Routing component requires that the parameters match the following regular expression: [^/]+. This means that all characters are allowed except /.

You must explicitly allow / to be part of your placeholder by specifying a more permissive regular expression for it:

1
2
3
4
5
6
7
8
9
10
11
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class DefaultController
{
    /**
     * @Route("/share/{token}", name="share", requirements={"token"=".+"})
     */
    public function shareAction($token)
    {
        // ...
    }
}

That's it! Now, the {token} parameter can contain the / character.

Note

If the route includes the special {_format} placeholder, you shouldn't use the .+ requirement for the parameters that allow slashes. For example, if the pattern is /share/{token}.{_format} and {token} allows any character, the /share/foo/bar.json URL will consider foo/bar.json as the token and the format will be empty. This can be solved replacing the .+ requirement by [^.]+ to allow any character except dots.

Note

If the route defines several placeholders and you apply this permissive regular expression to all of them, the results won't be the expected. For example, if the route definition is /share/{path}/{token} and both path and token accept /, then path will contain its contents and the token, and token will be empty.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version