Wildcard DNS, VirtualHosts on apache2, 404 for unused subdomains

apache-2.2http-status-code-404subdomainvirtualhostwildcard

On an Apache2 server linked to by a DNS that includes a wildcard entry, e.g. *.example.com, subdomains that are not defined as ServerNames in any VirtualHosts point to the first defined VirtualHost, in my example this is 000-default.

My Question:

How would one get unused subdomains (subdomains not used in any virtualhosts) to return a 404 error to the requesting client? This must preferably show in server logs as a 404 as well.

I have looked into the following possibilities:

  • Redirecting any invalid subdomain to the home page or some other page.

    The problem with this method is, when someone links to your site as this.company.sucks.example.com, the client will see your home page or in my case 000-default if I do not redirect. Thanks, to Mike for pointing this out. (regex for "suck", etc definately not an option)

  • Let the default VirtualHost point to a non-existent directory.

    Apache does not like this one bit, warning with every reload. Beyond the warning, everything seems fine. This seems like a hack. Does this seem like a problem (however small) to anyone?

  • Point the default VirtualHost to a folder where the index.php is forbidden, thus creating a 403 status code.

    This is confusing and makes things like the following overly complicated: Say, for example, you use a subdomain per user (a big reason to use wildcard DNS, apparently), and users have the ability to view each others profiles at username.example.com. This solution is confusing to the user and completely not what I want to do.

My ideal sollution will let the user know there is nothing to view at the url he entered. Preferably with a 404 and an error log entry for the address entered (not some other address).

Any help would be greatly appreciated!

Best Answer

I recently had the same issue and could not find a soultion until now. The best option turns out to be using

Redirect 404 /

or (as suggested earlier)

RedirectMatch 404 /.*

directive in the default (first) vhost, which obviously must be unused. The vhost can potentially be a 'fake' one, so something like following at the beginning of your vhost config file:

<VirtualHost *:80>
ServerName default #fake name, unused domains default here
Redirect 404 /
</VirtualHost>

<VirtualHost *.80>
ServerName example.tld
........
</VirtualHost>

Smells like a hack though.