Saturday 23 July 2011

Apache HTTP Server VirtualHost directive

Once of the things which always catches me out is the use of the VirtualHost directive in the configuration files for the Apache HTTP server. When you need to set up virtual hosting (i.e. more than one host off of the same IP, differentiated by the hostname) you need to use this directive. However, don't make the assumption that you can do something like:

<VirtualHost www.example.com>...</VirtualHost>

and that this will result in having a server defined for the 'www.example.com' hostname. The VirtualHost directive is used only to define the IP that this "virtual server" should listen on. It does not define which hostname it should reply to. While the above configuration is legal, the actual behaviour of Apache's HTTP Server is to lookup the hostname, convert it to an IP and use that in the directive. Functionally, it is no different than doing:

<VirtualHost [IP Address of www.example.com host]>...</VirtualHost>

Using the hostname in this part of the configuration might lead to some unexpected behaviour. For me, I added this directive with a hostname, expecting that the configuration section would only apply to a particular hostname, when in fact it matched all hostnames using that IP.

The correct way to define a hostname based virtual host is to make use of the ServerName and additionally ServerAlias directives inside the VirtualHost stanza.

No comments: