htaccess trick – redirect to WWW domain without hardcoding the domain name

I’m notoriously bad at writing good htaccess redirection rules, so when it came time to write a rule that would redirect any non-www URL to its www equivalent, I was a bit lost. I wanted a rule that I could apply to any website without needing to hard-code the domain. I found a few examples after some Google searching, but nothing worked for me. So, a colleague and I came up with this rule, which does the job:

RewriteCond %{HTTP_HOST} ^([a-z-]+)\.([a-z]{2,6})$ [NC]
RewriteRule ^(.*)$ http://www.%1\.%2/$1 [R=301,L]

Can it be improved? You tell me!

Leave a Reply