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!
1 Response to htaccess trick – redirect to WWW domain without hardcoding the domain name
Ollie Treend
May 14th, 2010 at 2:13 pm
I found this article a while back. It looks like it should do what you want.
http://www.workingwith.me.uk/blog/software/open_source/apache/mod_rewriting_an_entire_site
There’s also a rule to add a trailing slash if it’s been omitted, for example http://example.com/about would (should) get redirected to http://www.example.com/about/
Luckily for me CakePHP handles all the hardcore mod_rewriting!
So all I need to do is define a route and I’m away! Haha!