Clicky

Default Virtual Host in Apache

March 26, 2012

When using name-based virtual hosts, the first virtual host configuration loaded will be the default (Source: Apache Wiki). For example, with the configuration below, otherwise unmatched domains will match with domain-one.com:

NameVirtualHost *:80

<VirtualHost *:80>
  ServerName domain-one.com
  # Other options and directives ..
</VirtualHost>

<VirtualHost *:80>
  ServerName domain-two.com
  # Other options and directives ..
</VirtualHost>

Many servers do not have a monolithic configuration file, but have several host-specific configuration files organized as follows:

/etc/apache2
|-- sites_available  (actual configuration files)
`-- sites_enabled    (symlinks to files in sites_available)

In this case, to make a particular virtual host configuration load first, rename the symlink to something which will be first when sorted, such as 00-default.

Some suggestions offered elsewhere involve either not setting ServerName or using ServerAlias *, but neither of these are correct. According to the Apache Wiki, however, not setting a ServerName in a virtual host is incorrect. If the host without a ServerName is not loaded first, Apache may never even use it, since the first host loaded would be the default.

Furthermore, while ServerAlias * will indeed match anything, it may also override other virtual hosts defined later. Maybe this approach would work if it’s always the last virtual host to be defined, but this means adding a new directive and changing the sort order instead of just changing the order as above.