If you have a handful of urls that need https and some others that need http in your Symfony project then you’ll need to configure your project to set the scheme for your routes. Symfony outlines this in the Cookbook. The process is simple, just add a schemes line to your route configuration like this:

This will force the my_route route to use https. This solution is great if you have a small handful of routes, but what I’ve found is that when you force https on my_route and then navigate away using the links on the page you are stuck in https. Not a problem, maybe a minor performance hit but nothing major right? Well what if you then link to some other subdomains on your site that don’t share the SSL certificate? You are now introducing some certificate errors to your users.

A better solution to this is to use the app/config/security.yml file and add some routes to the access control section to force SSL instead of the routing files. To do so simply update your access control configuration to force the routes you need to https and then use a blanket route for the site to force http. This will keep only the urls you need SSL for in https and everything else unencrypted.

Notice that on all of the access control routes you need to specify a scheme using the requires_channel. Other than that consideration, you’re done. This method also means you don’t need to set the scheme for each route but you can simply pattern match your routes meaning much less configuration is needed, especially on larger sites with hundreds of routes.

One comment on “Force URLS to use HTTP or HTTPS in Symfony 2

  1. Doug says:

    If the protocol used for the route is http, can “requires_channel: http” be omitted? Ie, does it default to http?

Comments are closed.