How to match a route based on the Host

Version: 2.2
Edit this page

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

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

How to match a route based on the Host

New in version 2.2

Host matching support was added in Symfony 2.2

You can also match on the HTTP host of the incoming request.

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
mobile_homepage:
    path:     /
    host:     m.example.com
    defaults: { _controller: AcmeDemoBundle:Main:mobileHomepage }

homepage:
    path:     /
    defaults: { _controller: AcmeDemoBundle:Main:homepage }

Both routes match the same path /, however the first one will match only if the host is m.example.com.

Using Placeholders

The host option uses the same syntax as the path matching system. This means you can use placeholders in your hostname:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
projects_homepage:
    path:     /
    host:     "{project_name}.example.com"
    defaults: { _controller: AcmeDemoBundle:Main:mobileHomepage }

homepage:
    path:     /
    defaults: { _controller: AcmeDemoBundle:Main:homepage }

You can also set requirements and default options for these placeholders. For instance, if you want to match both m.example.com and mobile.example.com, you use this:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
12
mobile_homepage:
    path:     /
    host:     "{subdomain}.example.com"
    defaults:
        _controller: AcmeDemoBundle:Main:mobileHomepage
        subdomain: m
    requirements:
        subdomain: m|mobile

homepage:
    path:     /
    defaults: { _controller: AcmeDemoBundle:Main:homepage }

Tip

Make sure you also include a default option for the subdomain placeholder, otherwise you need to include the subdomains value each time you generate the route.

You can also use service parameters if you do not want to hardcode the hostname:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
mobile_homepage:
    path:     /
    host:     "m.{domain}"
    defaults: { _controller: AcmeDemoBundle:Main:mobileHomepage }
    requirements:
        domain: "%domain%"

homepage:
    path:  /
    defaults: { _controller: AcmeDemoBundle:Main:homepage }

Using Host Matching of Imported Routes

You can also set the host option on imported routes:

  • YAML
  • XML
  • PHP
1
2
3
4
# app/config/routing.yml
acme_hello:
    resource: "@AcmeHelloBundle/Resources/config/routing.yml"
    host:     "hello.example.com"

The host hello.example.com will be set on each route loaded from the new routing resource.

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