Jon Simpson
301 redirect from non-www to www
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. This might be advantageous for search engines, and help with cleaning up web server statistics.
The relevant .htaccess
magic to do the reverse, redirecting visitors using the www.example.co.uk form to example.co.uk is:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.co\.uk$ [NC]
RewriteRule ^(.*) http://example.co.uk/$1 [R=301,L]
Comments
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.
You’d have to use:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
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.
Thanks for the tip, i have used it on my paintings site to redirect the non www url to the www url. thanks
Will that work for all pages, or just the home page? I did it, and the only redirect I got is from http://example.com to http://www.example.com But not from http://example.com/page.html to http://www.example.com/page.html ??
The correct (and complete) form to use for non-www to www is:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*) http://www.example.com/$1 [R,L]
Similar, for www to non-www:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*) http://example.com/$1 [R=301,L]