How to Restrict Firewalls to a Specific Request

Version: 2.4
Edit this page

Warning: You are browsing the documentation for version 2.4 which is not maintained anymore.

If some of your projects are still using this version, consider upgrading.

How to Restrict Firewalls to a Specific Request

When using the Security component, you can create firewalls that match certain request options. In most cases, matching against the URL is sufficient, but in special cases you can further
restrict the initialization of a firewall against other options of the request.

Note

You can use any of these restrictions individually or mix them together to get
your desired firewall configuration.

Restricting by Pattern

This is the default restriction and restricts a firewall to only be initialized if the request URL
matches the configured pattern.

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
# app/config/security.yml

# ...
security:
    firewalls:
        secured_area:
            pattern: ^/admin
            # ...

The pattern is a regular expression. In this example, the firewall will only be
activated if the URL starts (due to the ^ regex character) with /admin. If the URL does not match this pattern, the firewall will not be activated and subsequent
firewalls will have the opportunity to be matched for this request.

Restricting by Host

New in version 2.4

Support for restricting security firewalls to a specific host was introduced in Symfony 2.4.

If matching against the pattern only is not enough, the request can also be matched against
host. When the configuration option host is set, the firewall will be restricted to
only initialize if the host from the request matches against the configuration.

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
# app/config/security.yml

# ...
security:
    firewalls:
        secured_area:
            host: ^admin\.example\.com$
            # ...

The host (like the pattern) is a regular expression. In this example, the firewall will only be activated if the host is equal exactly (due to the ^ and $ regex characters) to the hostname admin.example.com. If the hostname does not match this pattern, the firewall will not be activated and subsequent firewalls will have the opportunity to be matched for this request.

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