Redirect to www with htaccess

Many webmasters don’t take any steps to ensure their website is accessed with and not One reason to do this can include the presentation of your site in Google’s search results. Another reason is when you don’t control what address is presented, Google will make the decision for you. This can lead to issues with duplicate content, splitting of page rank and other SEO benefits, along with confusion when monitoring results in tools like Google Webmaster Tools.

When a person links to your site, they may simple link to Another person may link to This would be like looking at vs Google treats these as different websites and can be harmful to the overall rankings for your site. It is generally a good idea to decide if you want to redirect non www to www.

The solution to this is a rather easy htaccess rule. To setup a htaccess rule you would create a file called .htaccess in the root folder of your website, sometimes referred to public_html/, or htdocs/.

To enable mod_rewrite, enter this line first if it doesn’t exist already:

RewriteEngine on

Then you would put this below:
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

The first line reads the HTTP_HOST, and determines of the first 3 characters are www or not. If they are not, it continues onto the second line.

The second line takes the HTTP_HOST requested initially, and simply adds www. to it. The R=301 says that this is a HTTP code 301 permanent redirect, and the L tells the code to stop the rewriting process here and don’t apply any more rewrite rules.

To sum it up, a simple .htaccess file to redirect non www to www would be:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

It is also possible to redirect to The code below will do that:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

I hope this simple mod_rewrite rule will help when you decide to redirect non www urls to www, or the other way around.

Be Sociable, Share!
  1. #1 by John Sullivan on August 25, 2010 - 4:20 am

    That actually wont work for my site…. it says:

    The page isn’t redirecting properly

    Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

    * This problem can sometimes be caused by disabling or refusing to accept

  2. #2 by John Sullivan on August 25, 2010 - 4:42 am

    I figured it out, wp was already do it, so they were conflicting. I really like WP by the way.

  3. #3 by steve on August 25, 2010 - 10:02 am

    Great, I’m glad you’re taking a liking to WordPress.

    It’s definitely a lot easier to work with – once understood – than dealing with plane HTML files.

  4. #4 by Indyatech on October 4, 2011 - 8:06 pm

    thanks.. i did it for my company site.

Comments are closed.