How to Redirect from Your Root Domain to the WWW Subdomain

Wednesday, February 17, 2010 2:14
Posted in category PHP

How to Redirect from Your Root Domain to the WWW Subdomain and Vice Versa Using mod_rewrite?

Most websites stick to one form of their domain name when they refer to their own site, be it the plain domain name, like example.com, or the www form, like www.example.com. Unfortunately others linking to you don’t always follow your preferred style. If some sites link to you with just the domain name, and others link using the www subdomain, then your site may face issues with the search engines. This article shows you how you can work around the problem by automatically redirecting all URL requests of one form to the other in a search engine friendly way.

To redirect (say) example.com to www.example.com, add the following code to your .htaccess file.

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

The above code causes the server to check that the hostname in the URL is example.com. If it is, the visitor will be sent to www.example.com instead.

If you also own, say example.co.uk, example.de and/or some other domain, and want them to be redirected to www.example.com as well, you may prefer to use the following code instead:

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

To redirect any URL starting with (say) www.example.com to example.com, add the following code to your .htaccess file.

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

The above rules checks if the hostname in a URL contains www.example.com. If it does, the visitor is sent to example.com instead.

To use the rule, change all instances of "example.com" to your actual domain name. For the line beginning with RewriteCond, add a backslash ("\") before each of the full stops (or "periods") in your domain name.

You can leave a response, or trackback from your own site.

Leave a Reply

*