Default handling for unmatched domains/subdomains in Apache
I have an Apache2 configuration with multiple VirtualHosts. My DNS is set to accept *.<domain>.<tld>
on multiple domains. Everything is working correctly but if I go to something-random-here.example.com
I seem to get an invalid VirtualHost being selected (I am guessing the first or last one it finds). Is there a way to tell Apache to use certain rules if none of the VirtualHost entries match the domain or subdomain? I'd preferably like to return a 404.
Solution 1:
Apache uses the first virtualhost if no name matches. Just configure a new virtualhost as the first one with a random name, displaying whatever you like - or returning a 404 page.
Solution 2:
Wildcard include your site configuration files:
Include path/to/site/confs/*httpd.conf
Organize your site conf files so they are loaded in an expected order. Example...
01-httpd.conf
02-site1-httpd.conf
03-site2-httpd.conf
etc...
Apache will read these in order. Then create one that will always load last to catch any unmatched virtual hosts and return a 404 instead of loading a default site.
99-catchall-httpd.conf
<VirtualHost *:8080>
ServerName null
ServerAlias *
Redirect 404 /
</VirtualHost>
<VirtualHost *:8443>
ServerName null
ServerAlias *
Redirect 404 /
</VirtualHost>
Be sure to replace the ports with whatever ports your httpd listens on. Or if you have httpd listening on specific interfaces, you'll need to add a catchall for each interface instead, like so:
<VirtualHost 192.168.1.101:8080>
ServerName null
ServerAlias *
Redirect 404 /
</VirtualHost>
<VirtualHost 192.168.1.101:8443>
ServerName null
ServerAlias *
Redirect 404 /
</VirtualHost>
<VirtualHost 192.168.1.102:8080>
ServerName null
ServerAlias *
Redirect 404 /
</VirtualHost>
<VirtualHost 192.168.1.102:8443>
ServerName null
ServerAlias *
Redirect 404 /
</VirtualHost>
Hope this helps. I use this method to load sites in the order I specify and prevent unmatched virtual hosts from loading an unexpected site unintentionally.