Apache 2 catch all virtualhost

Apache 2 catch all virtualhost

Tags :

Category : How-to

Get Social!

Background

Apache VirtualHosts are something of a must for running multiple sites with different web address, all under the same physical server. Using VirtualHost tags you can easily direct traffic for www.domain1.com to one location, and www.domain2.com to another even when both domains point to the same IP address.

I am not going to detail VirtualHost directives here, however I will tell you about the recent issue I had with subdomains and this very blog. A long time ago I had a subdomain redirect.jamescoyle.net which is no longer in use. At the time, Google got hold of this and kindly indexed it for search. The trouble was that redirect.jamescoyle.net points to the same IP address as www.jamescoyle.net even though it is no longer in use. Apache used to be set up to handle the two sub-domains differently but the VirtualHost entry for redirect has since been removed. This means that Google now has an index of this blog on both www.jamescoyle.net and redirect.jamescoyle.net – not ideal to say the least.

What I needed was something which took users of www.jamescoyle.net to this blog, and redirect all other sub-domains to it. After trying numerous directives and ServerName/ ServerAlias options I stumbled upon the answer.

The Interesting Stuff

Apache will respect any ServerName or ServerAlias option until a domain is used which doesn’t match any VirtualHost. When this happens, the very first VirtualHost for that port (usually port 80 for http) is used as a ‘catch all’.

For RHEL based flavours of Linux, it would make sense to add the ‘catch all’ as the first VirtualHost entry in httpd.conf. For Debian based distributions, the default and default-ssl would be the place as these files have a symlink starting with 000 meaning it will likely be loaded first.

To illustrate the resulting configuration, see the below (albeit simplified) files in sites-available/

NameVirtualHost *:80 
<VirtualHost *:80>
 DocumentRoot /var/www
 Redirect permanent / http://www.jamescoyle.net/ 
</VirtualHost>
<VirtualHost *:80>
 ServerName www.jamescoyle.net
 DocumentRoot /var/www
 <Directory /var/www/>
 Options Indexes FollowSymLinks MultiViews
 AllowOverride None
 Order allow,deny
 allow from all
 </Directory>
</VirtualHost>

All requests for www.jamescoyle.net will be managed by the second entry and all other domains will be managed by the first and redirected to www.jamescoyle.net. Give it a go: abcdefg.jamescoyle.net


Leave a Reply

Visit our advertisers

Quick Poll

Which type of virtualisation do you use?
  • Add your answer

Visit our advertisers