Redirecting from non-www to www domains in Apache

Published:
Updated:
In my time as an SEO for the last 2 years and in the questions I have assisted with on here I have always seen the need to redirect from non-www urls to their www versions.

For instance redirecting
http://domain.com
to
http://www.domain.com

From a Search Engine Optimisation perspective I recommend this as Search Engines may see this as 2 separate URLs serving the same content. In this case we would need to perform a server side 301 redirect. We use a 301 redirect for this because if any links that are passing PR have been pointed to the non-www version it will be transferred over time to the www version of the URL. I you were to use a 302 redirect you would not pass this important information over to the www version.

To create this redirect is simple. on your server you need to locate your .htaccess file and open it in your choice of text editor.

For going from non-www to www you will need to use the below lines and change domain.com for your domain name and TLD.
 
RewriteEngine on
                      RewriteCond %{HTTP_HOST} ^domain.com [NC]
                      RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]

Open in new window


This will then work on all pages within your site for instance
http://domain.com/somefolder/anotherone/
would redirect to
http://www.domain.com/somefolder/anotherone/

If however you wanted to remove the www's from all of your URL's you would use the below lines  and also change the domain and TLD.
 
RewriteEngine on
                      RewriteCond %{HTTP_HOST} ^www.domain.com [NC]
                      RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

Open in new window


Shane Jones
2
9,426 Views

Comments (2)

Hi,

I was searching for some PAQs regarding non-www to www redirects for Apache. All talk about .htaccess redirect. But, my host does not allo mod-rewrite. Do you have any suggestions for this? If I upload .htaccess file, my website gives "internal server error".

Thanks.

Commented:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]

Open in new window


It's a bit safer to use a negation instead, otherwise you won't catch ww.domain.com or w.domain.com.

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.