StackArena | Redirecting To www With .htaccess

Editor’s Note: Really excited to be publishing a first post from our partnership with StackArena. With aligning goals, oTeKbits has partnered with StackArena in the area of developing a pure developer community – for both pros, and prospects, while sharing quality resource that will help with development. Enjoy:

Redirecting to a specific domain is an important part of web development. Suppose you have a domain name:, users can either type this or 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 is different from so also is 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 site to the 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.
$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

RewriteEngine On 
RewriteCond %{HTTP_HOST} !^$ [NC] 
RewriteRule ^(.*)$$1 [R=301,L]

In this case, replace with your actual domain name.

Source: StackArena


Comments are closed.