Define a Catch-all Named Virtual Host in Apache

Let say you have 2 virtual hosts A.com and B.com on your web server, do you know that it is possible that your visitor may accidentally access A.com while browsing B.com? As a best practice, defining a catch-all Virtual host can prevent such scenario.

Example virtual host config:

How does it went wrong

Apache Named Virtual hosts works as follows, the first virtual host is always assumed as the “default server”. If a new domain C.com is pointed to your IP but you haven’t defined a virtual host for that, when the user enter C.com in their browser, the content of A.com will be served!

My Solution

I don’t know if this is the best solution, but it works for me. The way it works is that the Catch-all virtual host must be defined last. Under CentOS, apache will load the conf files under /etc/httpd/conf.d in alphabetical order, so using the zzz_ prefix can usually make sure the file is loaded last. If you like to put all your vhosts in one conf file, then put this at the very end of the file

/etc/httpd/conf.d/zzz_default_vhost.conf

Save it and reload apache

 

One Reply to “Define a Catch-all Named Virtual Host in Apache”

Share your thoughts