[How to] Redirecting non-www URLs to www URLs and vice versa using .htaccess

Started by Xhanch Studio, March 25, 2011, 01:18:12 AM

previous topic - next topic
Go Down

Xhanch Studio

The Apache Web server supports URL rewriting with the mod_rewrite engine. Placing custom rules in an .htaccess file lets you do all sorts of useful things to keep your URLs tidy. One really handy thing you can do for search engines and visitors is redirecting traffic from www to non-www version of your domain (and vice versa).

Some people prefer to use www.example.com, but some people prefer the shorter example.com. There isnââ,¬â,,¢t really a right or wrong way to do it, but whatever you choose you can make sure all of your visitors get sent to the same place. With a few simple rules on the server you can choose from non-www to www, or redirecting from www to non-www.

If you already have a file named .htaccess on your website root directory, you can add to it. If not, create one (yes, include the period at the beginning). Add either of the following rules and save. Replace example.com with your actual domain name.

Redirect www URLs to non-www URLs:

Code Select
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

Code Select
RewriteEngine On
RewriteBase /
RewriteCond % ^www.example.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

Redirect non-www URLs to www URLs:

Code Select
RewriteEngine On
RewriteBase /
RewriteCond % ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

Both of these rules send a full search engine friendly 301 HTTP redirect. They also preserve the entire URL (so example.com/about redirects to www.example.com/about).

Search engines can usually figure out which format is preferred, but since youââ,¬â,,¢re showing the same page for www and non-www URLs it canââ,¬â,,¢t hurt to be consistent about it.
Best Regards,
Susanto B.Sc
Web development services, WordPress plugin and theme development, PSD to XHTML conversion - http://xhanch.com
Read free manga online - http://authrone.com

Go Up