Redirecting to www with .htaccess

Redirecting to a specific domain is an important part of web development. Suppose you have a domain name: my-domain-name.com, users can either type this or www.my-domain-name.com to access your website. Although they see the same website either way but this might have some terrible consequences.

Three reasons why you should maintain a specific domain

To avoid the possibility of split page rank and/or split link popularity (inbound links). Though the two names bring similar result, they are actually two different domains. Just has m.my-domain-name.com is different from www.my-domain-name.com so also is my-doman-name.com different from the rest.

To avoid duplicate content on search engines. Search engines might be able to tell the difference between these two domains and hence record duplicate content of your site.

Its nicer and consistent. If you create a session for user, you expect it to be consistent across the browser tabs. Not using a specific domain could cause such inconsistency. If you have a link on your my-domain-name.com site to the www.my-domain-name.com or the user decides to append the , the user’s session will not be found on the www version.

Redirecting non-www to www

If you want to redirect all non-www requests to your site to the www version, add the following code to your .htaccess file:

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

Translates to:
RewriteEngine On checks if the rewrite module is on else the other lines will not be processed.
! = not
^ = start
\. = . (the backslash is the escape character, because dots mean “any character” in regular expressions, and therefore must be escaped)

RewriteCond %{HTTP_HOST} !^www\. if the host name doesn’t start with www.
* means zero or more character
$ means end
(.*) means zero or more characters

RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] %{HTTP_HOST} will be replaced by the host name (i.e. my-domain-name.com).
$1 references whatever was matched in the regular expression between the brackets, which in this case is everything.
The [R=301,L] means a permanent redirect (HTTP 301 code) which means the browser will automatically redirect the next time

Redirecting www to non-www

Like twitter, you might prefer the my-domain-name over www.my-domain-name.com.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^my-domain\.com$ [NC]
RewriteRule ^(.*)$ http://my-domain.com/$1 [R=301,L]
In this case, replace my-domain-name.com with your actual domain name.

A Web designer and developer. Speaks PHP, Java, Javascript, HTML

Leave a Reply

Your email address will not be published. Required fields are marked *