Redirect Wildcard- or Sub-Domains to Main Site with Apache

If you want to re-direct users from your subdomain(s) to your main site you can use a virtual host configuration like this:

<VirtualHost *:80>
  ServerName www.ten-fingers-and-a-brain.com
  ServerAlias *.ten-fingers-and-a-brain.com
  Redirect permanent / http://ten-fingers-and-a-brain.com/
</VirtualHost>

If you want to have the main site under the www name you should change the configuration like this:

<VirtualHost *:80>
  ServerName ten-fingers-and-a-brain.com
  ServerAlias *.ten-fingers-and-a-brain.com
  Redirect permanent / http://www.ten-fingers-and-a-brain.com/
</VirtualHost>

Please make sure that your main site comes before this one in the configuration, e.g. by placing it at the top of the same file.

You thought WordPress does this without additional configuration? Well, you’re generally right, but if you let WordPress do the work that’s one extra round of loading PHP and connecting to the database. My approach is much faster and causes less server load.

Why bother? For instance because Google or Bing will not see duplicate content, both under the main site and the www subdomain. Avoiding duplicate content has a positive effect on your ranking in search results.

Tags:

Reply

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