You are browsing the Symfony 4 documentation, which changes significantly from Symfony 3.x. If your app doesn't use Symfony 4 yet, browse the Symfony 3.4 documentation.
How to Restrict Route Matching through Conditions
How to Restrict Route Matching through ConditionsΒΆ
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 conditions
routing option:
- YAML
1 2 3 4 5
# config/routes.yaml contact: path: /contact controller: 'App\Controller\DefaultController::contact' condition: "context.getMethod() in ['GET', 'HEAD'] and request.headers.get('User-Agent') matches '/firefox/i'"
- XML
1 2 3 4 5 6 7 8 9 10 11 12
<!-- config/routes.xml --> <?xml version="1.0" encoding="UTF-8" ?> <routes xmlns="http://symfony.com/schema/routing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd"> <route id="contact" path="/contact"> <default key="_controller">App\Controller\DefaultController::contact</default> <condition>context.getMethod() in ['GET', 'HEAD'] and request.headers.get('User-Agent') matches '/firefox/i'</condition> </route> </routes>
- PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// config/routes.php use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; $routes = new RouteCollection(); $routes->add('contact', new Route( '/contact', array( '_controller' => 'App\Controller\DefaultController::contact', ), array(), array(), '', array(), array(), 'context.getMethod() in ["GET", "HEAD"] and request.headers.get("User-Agent") matches "/firefox/i"' )); return $collection;
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 Request).
Caution
Conditions are not taken into account when generating a URL.
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.