Wednesday, April 7, 2010

Redirect To SSL Using Apache’s .htaccess

SkyHi @ Wednesday, April 07, 2010





There are plenty of times I want to require users to be accessing a site only via SSL. My first try at this was to simple create a .htaccess file that contained SSLRequireSSL, which basically tells Apache that access to a site can only be allowed if SSL is being used. This accomplished what I wanted, but it brought a side issue to requiring SSL, users often leave off (or forget) the the s in https. So after a little bit of digging around I found another approach to this. The new .htaccess file looks like this:

RewriteEngine On
RewriteCond %{SERVER_PORT} !443
RewriteRule (.*) https://www.example.com/require-secure/ [R]

The first line tells Apache we are going to use mod_rewrite. The second line only matches if the port being used to access the site is 443 (the port reserved for https use). If that second line matches then the third takes kicks in, which simply redirects the user to the SSL version of your URL. This still enforces the use of SSL, but saves you from trying figure why you can’t get to your site just because you forget the s in https.

UPDATE Tue 23 May 2006 @ 3:50pm : Comment #4 by Nicolás Echániz has an even better version of this that isn’t limited to checking a specific port (443) for SSL:


RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

REFERENCE
http://joseph.randomnetworks.com/archives/2004/07/22/redirect-to-ssl-using-apaches-htaccess/