Set the Web Server to Use the Domain Without www

The main reason to bother with this is to help search rankings. Sub-domains (for example, and are treated as separate websites even if you have entirely the same content displayed for both. If 20% of the links to your site use the www and 80% don’t then your sites ranking by search engines is less than it would be if it was just treated as one site.

You can set the domain to use in Google webmaster tools. But that doesn’t do anything for all the other search engines. Also if you have both, some reports some will keep statistics separately for the non-www and www domain (Google Adsense does this, for example).

Using virtual hosts file (sites-enabled)

For Apache you can place the following code in your virtual hosts file (in the sites-available directory under Apache).

Replace with your domain name.

[bash]<Directory /srv/www/>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^$ [NC]
RewriteRule ^(.*)$$1 [R=301,L]

Then you need to capture the update and reload Apache.

Disable the site (in order to enable it with the updates)
[bash]sudo a2dissite[/bash]
Enable the site
[bash]sudo a2ensite[/bash]
Reload Apache (new way – Ubuntu 12.04)
[bash]sudo service apache2 reload[/bash]
Old way to reload Apache was > sudo /etc/init.d/apache2 reload

If when you try to reload you get this error message:

“Invalid command ‘RewriteEngine’, perhaps misspelled or defined by a module not included in the server configuration” then enable modrewrite on apache:

[bash]sudo a2enmod rewrite[/bash]

You should then be told to restart apache

[bash]sudo /etc/init.d/apache2 restart[/bash]

Using .htaccess

Or you can include the following in your .htaccess file

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

Related: Checklist for Setting Up a New Domain on VPSPhusion Passenger Tips and Troubleshooting Ideas

If you wanted to force www to be used instead just flip the regular expression around:

[bash]<Directory /srv/www/>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^$ [NC]
RewriteRule ^(.*)$$1 [R=301,L]

Leave a Reply

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

This Blog will give regular Commentators DoFollow Status. Implemented from IT Blögg