Wednesday, October 28, 2009

Setting up automatic 'ssl' via htaccess

Very easy to do using rewrite rules:

RewriteEngine On
RewriteBase /
# First rule, forward pages that are not allowed to be
# over http
RewriteCond %{HTTPS} =off
RewriteRule ((sell|register)\.php) https://www.website.com/$1 [R,L,QSA]
# Second rule, forward any pages that are not allowed
# to be accessed over https back to http.
RewriteCond %{HTTPS} =on
RewriteCond %{REQUEST_URI} !((suburb|sell|register)\.php)
RewriteRule (.*\.php) http://www.website.com/$1 [R,L,QSA]

The first RewriteCond and RewriteRule redirects the sell.php, register.php pages to https.

The second RewriteRule redirects all php pages back to http unless they are allowed to be accessed via https.You'll notice that I've got an extra page called suburb.php that can be accessed via http or https; this is because it is accessed via ajax - https javascript is picky.