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 http://www.example.com>…</VirtualHost&gt;

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 http://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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.