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:
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. 🙂
3 comments
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 }
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!
Here another solution using virtual host configuration file
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [NE]
Using path(‘some_route’) instead of url(‘some_route’) in twig, more information in docs: http://symfony.com/blog/new-in-symfony-2-2-new-url-generation-options (symfony >= 2.2)
Cheers