Mikkel Høgh

Protecting your users from phishing with Apache rules and HSTS

HTTP Strict Transport Security or HSTS is a new security feature in browsers that enables you tell the browser “always use SSL when accessing this site”.

Mozilla has a good blog post explaining HSTS, so I won’t try to replicate that here, but I’d just like to make it clear that if you have a site that should always use SSL, be it Drupal or Django or any other system, this is definitely something you should get set up.

Good examples of these are webmail, server administration and monitoring tools and general admin backends. If you are running a large Drupal-site, you should perhaps consider restricting admin-access to a SSL-protected subdomain.

Currently, it is only supported in Chrome 4 and above, and Firefox 4 beta 5 and beyond, but hopefully the other browser makers will catch up soon. Its fully backwards compatible, in that it will have no effect if the browser does not support HSTS.

How to use it

Setting it up is very simple. In your Apache VHost, where you do your SSL config, just add this line:

Header add Strict-Transport-Security "max-age=15768000"

This will tell the browser to remember that this site is SSL/HTTPS only for the next 6 months. During that time it will simply rewrite any and all requests to that site to use HTTPS instead of HTTP without ever communicating insecurely with the server.

If you use nginx, the syntax is subtly different. Adding this to the server section does the trick:

add_header Strict-Transport-Security max-age=15768000;

Keep your redirects

An important point is that HSTS only works after the user has received the header via HTTPS. So you will still need to have a redirect from your HTTP-site to HTTPS, also for supporting browsers that still do not understand HSTS.

This is easily accomplished using Apache’s mod_rewrite:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTPS} off
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</IfModule>

Thus, with a few lines of configuration, you can make the web a safer place to be for your users. So, what are you waiting for?