Symfony2 force HTTPS with .htaccess

© CDWaldi@sxc.hu

Lots of posts are written on forcing HTTPS on routes, but I didn’t find one that is suitable for my Symfony2 installation, so I tried to write combination that will work for my project.

Of course I included folowing inside security.yml:

access_control:
  - { path: ^/admin.*, roles: ROLE_ADMINISTRATOR, requires_channel: https}

For some reason default redirection to https when user enters http:// route is not working, so in my case both: http:// and https:// are available on server to the visitors.

So to force https:// in every case I changed my .htaccess file little bit:

RewriteEngine On

RewriteCond %{HTTPS} !=on

RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*)$ app.php [QSA,L]

Of course, there is another option in Symfony to force HTTPS on routes and requires putting _scheme: https requirement inside routing.yml or route annotations like this:

_api_v1_get_user_locations:
pattern:  /v1/locations/{_locale}.{_format}
defaults: { _controller: SurgeworksApiBundle:Locations:getUserLocations, _format: json, _locale: en}
requirements:
   _method:  GET
   _scheme: https

Using this approach, we can choose individual routes that will use https protocol.

Cheers. 🙂

You made it all the way down here so you must have enjoyed this post! You may also like:

Symfony, HWIOAuthBundle and Google Sign-in Branko Ajzele
Branko Ajzele, | 14

Symfony, HWIOAuthBundle and Google Sign-in

Symfony2 –  remember me cookies Darko Goles
Darko Goles, | 2

Symfony2 – remember me cookies

Symfony2 DBAL QueryBuilder Darko Goles
Darko Goles, | 6

Symfony2 DBAL QueryBuilder

3 comments

  1. More flexibility solution is:

    How to Force HTTPS or HTTP for different URLs – https://symfony.com/doc/current/security/force_https.html

    # config/packages/security.yaml
    security:
    # …
    access_control:
    – { path: ^/secure, roles: ROLE_ADMIN, requires_channel: https }
    – { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
    # catch all other URLs
    – { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }

  2. Thank you very much, because of you i do not have to invent the wheel again :-). It works perfectly just place it in top of the existing .htaccess file. Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.