How to Force HTTPS or HTTP for different URLs

How to Force HTTPS or HTTP for different URLs

Tip

The best policy is to force https on all URLs, which can be done via your web server configuration or access_control.

You can force areas of your site to use the HTTPS protocol in the security config. This is done through the access_control rules using the requires_channel option. To enforce HTTPS on all URLs, add the requires_channel config to every access control:

  • YAML

    1. # config/packages/security.yaml
    2. security:
    3. # ...
    4. access_control:
    5. - { path: '^/secure', roles: ROLE_ADMIN, requires_channel: https }
    6. - { path: '^/login', roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
    7. # catch all other URLs
    8. - { path: '^/', roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
  • XML

    1. <!-- config/packages/security.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <srv:container xmlns="http://symfony.com/schema/dic/security"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:srv="http://symfony.com/schema/dic/services"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd">
    8. <config>
    9. <!-- ... -->
    10. <rule path="^/secure"
    11. role="ROLE_ADMIN"
    12. requires-channel="https"/>
    13. <rule path="^/login"
    14. role="IS_AUTHENTICATED_ANONYMOUSLY"
    15. requires-channel="https"
    16. />
    17. <rule path="^/"
    18. role="IS_AUTHENTICATED_ANONYMOUSLY"
    19. requires-channel="https"
    20. />
    21. </config>
    22. </srv:container>
  • PHP

    1. // config/packages/security.php
    2. $container->loadFromExtension('security', [
    3. // ...
    4. 'access_control' => [
    5. [
    6. 'path' => '^/secure',
    7. 'roles' => 'ROLE_ADMIN',
    8. 'requires_channel' => 'https',
    9. ],
    10. [
    11. 'path' => '^/login',
    12. 'role' => 'IS_AUTHENTICATED_ANONYMOUSLY',
    13. 'requires_channel' => 'https',
    14. ],
    15. [
    16. 'path' => '^/',
    17. 'role' => 'IS_AUTHENTICATED_ANONYMOUSLY',
    18. 'requires_channel' => 'https',
    19. ],
    20. ],
    21. ]);

To make life easier while developing, you can also use an environment variable, like requires_channel: '%env(SECURE_SCHEME)%'. In your .env file, set SECURE_SCHEME to http by default, but override it to https on production.

See How Does the Security access_control Work? for more details about access_control in general.

Note

An alternative way to enforce HTTP or HTTPS is to use the scheme option of a route or group of routes.

Note

Forcing HTTPS while using a reverse proxy or load balancer requires a proper configuration to avoid infinite redirect loops; see How to Configure Symfony to Work behind a Load Balancer or a Reverse Proxy for more details.

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