Secure Certificates and missing www

April 27, 2009 – 10:00 pm

Thanks to forgiving server-configurations it usually doesn’t matter whether you access a website via the fully qualified URL including “www” or without it - requests to http://codemassacre.com and www.codemassacre.com are taking you to the same place. After all you want to make it as easy as possible for people to access your website, so being forgiving is important.

However, as soon as you try to secure your site with help of a secure certificate and the corresponding https protocol, you need to pay closer attention, and, ultimately, make a choice as to which domain name the certificate applies to, because it will be either with www, or without.

Specifically, requesting https://some-domain.com for a site that only has a certificate for https://www.some-domain.com will cause your browser to raise a warning about an invalid certificate and block the site - certainly not a trust-invoking impression to give a potential customer! (unfortunately I am speaking first hand here, hehehe ;)

So, long story short, here’s an .htaccess entry that forces all requests to your site to have a www at the beginning:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^some-domain.com
RewriteRule (.*) http://www.some-domain.com/$1 [R=301,L]

What’s happening here is that  we’re watching the HTTP_HOST server variable for anything that starts with “some-domain.com”. The ^ signifies the beginning of a string. If this condition is fulfilled, we rewrite any request (.*) to the fully qualified url, and we append whatever was matched by the (.*) part - which goes into the $1 variable. Lastly, we set the R=301 flag to tell the client browsers that this redirect is permanent. The L is for good taste to make sure this is the last rule applied to this request (no point in applying any other rules..).

Now requests to https://some-domain.com will be redirected to https://www.some-domain.com, the certificate matches, and the browser is happy - and so is whoever visited your site, because as we all know “ignorance is bliss” ;)


Filed under: Rnadom Sftuf — Tags: , , — by Richtermeister

Powered by WordPress