Thursday, April 1, 2010

Redirect non www to www for all sites using .htaccess

If you just have a few site its easy to modify .htaccess to redirect all URL to start with WWW, just type in the following in .htaccess (if you don't have one, you can create using notepad and save it as .htaccess then upload to your server root directory):

Options +FollowSymLinks

RewriteEngine On

RewriteCond %{HTTP_HOST} ^yoursitenamehere.com
RewriteRule ^(.*)$ http://www.yoursitenamehere.com/$1 [R=permanent,L]

When peoples visit http://yoursitenamehere.com, it'll automatically redirect them to http://www.yoursitenamehere.com

Its an easy process that doesn't take lots of time to do it, but what if you build hundreds of site. Are you going to change them one by one? You could, but its a time consuming and tedious task. You can make it easier by using the following code in .htaccess

Options +FollowSymLinks

RewriteEngine On

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

As you can see above, you are not require to put in your domain name. But it'll work the same as the first one, and have been tested by me. Let me know if you experience any trouble with it.