Jon Simpson

301 redirect from non-www to www

19 Feb 2006 — apache, htaccess, web server

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.

{literal} RewriteEngine On RewriteCond %{HTTP_HOST} ^example.co.uk RewriteRule (.*) http://www.example.co.uk/$1 [R=301,L] {/literal}

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:

{literal} RewriteEngine On RewriteCond %{HTTP_HOST} ^www.example.co.uk$ [NC] RewriteRule ^(.*) http://example.co.uk/$1 [R=301,L] {/literal}

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.

Paul Findlay, 01 Apr 2006


You’d have to use: {literal} RewriteEngine On RewriteCond %{HTTP_HOST} ^www.example.com$ [NC] RewriteRule ^(.*)$ http://example.com/$1 [R=301,L] {/literal}

Michael Benson, 21 Jun 2006


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.

Yan, 23 Mar 2007


Thanks for the tip, i have used it on my paintings site to redirect the non www url to the www url. thanks

Art - 10 Aug 2006


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 ??

Lior - 21 Jun 2006


The correct (and complete) form to use for non-www to www is: {literal} RewriteEngine On RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteRule ^(.*) http://www.example.com/$1 [R,L] {/literal}

Similar, for www to non-www:

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

Huskey - 19 Jan 2008



 Home