Symfony2 force HTTPS with .htaccess

Symfony2 force HTTPS with .htaccess ©

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:

  - { 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:

pattern:  /v1/locations/{_locale}.{_format}
defaults: { _controller: SurgeworksApiBundle:Locations:getUserLocations, _format: json, _locale: en}
   _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


  1. More flexibility solution is:

    How to Force HTTPS or HTTP for different URLs –

    # config/packages/security.yaml
    # …
    – { 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 }

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>.

Tell us about your project

Drop us a line. We'd love to know more about your project.