Apache 2 catch all virtualhost

Apache 2 catch all virtualhost

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/

default

1

2

3

4

5

NameVirtualHost*:80

<VirtualHost*:80>

DocumentRoot/var/www

Redirectpermanent/http://www.jamescoyle.net/

</VirtualHost>

www.jamescoyle.net

1

2

3

4

5

6

7

8

9

10

<VirtualHost*:80>

ServerNamewww.jamescoyle.net

DocumentRoot/var/www

<Directory/var/www/>

OptionsIndexesFollowSymLinksMultiViews

AllowOverrideNone

Orderallow,deny

allowfromall

</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