Knowledgebase
How to use mod_rewrite to force yourdomain.com to open as www.yourdomain.com and vice versa
If you want requests for yourdomain.com to be opened and displayed in the client's browser as www.yourdomain.com, or the other way around, you can do it with the help of mod_rewrite.
What you need to do is to place a few directives in the .htaccess file that's in the public_html directory of your hosting account.
If you want all requests for yourdomain.com be redirected to www.yourdomain.com, you can use the following directives:
#Force yourdomain.com to be opened as www.yourdomain.com RewriteEngine On RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*) http://www.yourdomain.com/$1 [R,L]The RewriteCond directive will match if the request starts without www. Then the RewriteRule will be applied redirecting it to www.yourdomain.com. This includes any files and subdirectories, so for example yourdomain.com/folder/index.html will be opened as www.yourdomain.com/folder/index.html.
If you want to, you can do the opposite. You can force www.yourdomain.com to be opened as yourdomain.com. You can achieve this with a few minor changes to the above directives. The exclamation mark in front of www in the RewriteCond directive makes it a negative match, meaning that the condition will be fulfilled if the hostname starts without www. So you just have to remove the exclamation mark and in the RewriteRule directive you need to remove www from the destination URL address. This means that requests for www.yourdomain.com will be opened as yourdomain.com. The directives should look like this:
#Force www.yourdomain.com to be opened as yourdomain.com RewriteEngine On RewriteCond %{HTTP_HOST} ^www\. [NC] RewriteRule ^(.*) http://yourdomain.com/$1 [R,L]For details about the mod_rewrite directives and their syntax check out the tutorial on mod_rewrite.