## Redirect non-www domain to www in Apache

By admin | January 24, 2011

Search engines will often consider the non-www and www sites of a domain as separate websites (example.com vs www.example.com). In order to solve this, you will often want to redirect the non-www part of the website (example.com) to the www part (www.example.com). So this way if your visitor types example.com or www.example.com they will wind up at your home page at www.example.com.

First have your site configuration file (with the VirtualHost) opened in your favourite text editor, then make sure the ServerName of the VirtualHost is set to the www version:

<VirtualHost *:80>
ServerName www.example.com

<!-- other VirtualHost configs here... -->
</VirtualHost>


Then add another VirtualHost at the bottom of that (in the same file), replacing your variables:

<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>


This should look something like this in the end (all in one file):

<VirtualHost *:80>
ServerName www.example.com

<!-- other VirtualHost configs here... -->
</VirtualHost>

<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>


When you are done save the file, close it and reload Apache:

sudo /etc/init.d/apache2 reload

This is a very safe and effective way to enforce your SEO and this solution does not require the rewrite engine either, which makes it very fast and safe. It performs the 301 redirect in the search-engine-approved manner and it will make sure your search engine popularity is not being cut in half by the www and non-www.