Skip to content

How to Restrict Route Matching through Conditions

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

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

A route can be made to match only certain routing placeholders (via regular expressions), HTTP methods, or host names. If you need more flexibility to define arbitrary matching logic, use the condition routing setting:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/Controller/DefaultController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;

class DefaultController extends Controller
{
    /**
     * @Route(
     *     "/contact",
     *     name="contact",
     *     condition="context.getMethod() in ['GET', 'HEAD'] and request.headers.get('User-Agent') matches '/firefox/i'"
     * )
     *
     * expressions can also include config parameters
     * condition: "request.headers.get('User-Agent') matches '%app.allowed_browsers%'"
     */
    public function contact()
    {
        // ...
    }
}

The condition is an expression, and you can learn more about its syntax here: The Expression Syntax. With this, the route won't match unless the HTTP method is either GET or HEAD and if the User-Agent header matches firefox.

You can do any complex logic you need in the expression by leveraging two variables that are passed into the expression:

context
An instance of RequestContext, which holds the most fundamental information about the route being matched.
request
The Symfony Request object (see The HttpFoundation Component).

Caution

Conditions are not taken into account when generating a URL.

Behind the scenes, expressions are compiled down to raw PHP. Our example would generate the following PHP in the cache directory:

1
2
3
4
5
6
if (rtrim($pathInfo, '/contact') === '' && (
    in_array($context->getMethod(), [0 => "GET", 1 => "HEAD"])
    && preg_match("/firefox/i", $request->headers->get("User-Agent"))
)) {
    // ...
}

Because of this, using the condition key causes no extra overhead beyond the time it takes for the underlying PHP to execute.

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