<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

Redirecting from non-www to www domains in Apache

Published on
12,304 Points
8,604 Views
2 Endorsements
Last Modified:
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
Author:ShaneJones
2 Comments
LVL 3

Expert Comment

by:shrishti132
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.
0
LVL 3

Expert Comment

by:cduke250
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.
0

Featured Post

JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

Learn the basics of Skype For Business in office 365
Please check the video also in regards to recovery of deleted emails from office 365 admin center and through the MFCMAPI tool. I have mentioned each and every step with the proper steps that need to be taken care of.
Other articles by this author

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month