301 redirect non-www to www
In continuation of the theme ‘using my blog as a personal notepad’, here’s a small snippet for use in an Apache .htaccess file to ensure that visitors/incoming links not using the www. form of your site’s domain are redirected correctly.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.co\.uk
RewriteRule (.*) http://www.example.co.uk/$1 [R=301,L]
Make sure to escape periods in the RewriteCond line with backslashes. Reasons you might wish to do this mostly relate to search-engine friendliness and unity of web stats.
Previous: Wordpress with Subversion: Upgrades Next: On robotics abstractions (or how robots can’t take over the world, yet)

What would the reverse of this be? i.e. if you wanted to send all visitors to http://www.example.co.uk to http://example.co.uk
April 1st, 2006 at 1:52 am
You’d have to use;
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
RewriteRule ^(.*)$ http://domain.com/1 [R=301,L]
June 21st, 2006 at 4:00 pm
Thanks for the tip. Just did it on my sites. Was losing a lot of backlink juice because some would bookmark as www, while some w/o it.
March 23rd, 2007 at 10:08 pm
Thanks for the tip, i have used it on my paintings site to redirect the non www url to the www url.
thanks
August 10th, 2007 at 6:54 pm
Will that work for all pages, or just the home page?
I did it, and the only redirect I got is from http://domain.com to http://www.domain.com
But not from http://domain.com/page.html to http://www.domain.com/page.html
??
December 22nd, 2007 at 1:12 pm
The correct (and complete) form to use for non-www to www is:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com [NC]
RewriteRule ^(.*) http://www.domain.com/1 [R,L]
Similar, for www to non-www:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.domain\.com [NC]
RewriteRule ^(.*) http://domain.com/1 [R=301,L]
The $ sign marks a line end, therefore your rule will never trigger for a http://domain.com/something page.
January 19th, 2008 at 12:44 am
Sorry for double post. http gets translated to a link and deletes the $.
RewriteRule ^(.*) http://domain.com/1 [R=301,L]January 19th, 2008 at 12:49 am