Wildcard DNS, VirtualHosts on apache2, 404 for unused subdomains

Solution 1:

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.

Solution 2:

You can setup a default virtual host with the following according to the Apache docs:

RedirectMatch 404 /.*

http://httpd.apache.org/docs/2.2/mod/mod_alias.html#redirect

Let me know if it doesn't work.

Solution 3:

This might help: I was trying to solve a wildcard subdomain problem I set myself earlier, and found some example code from webmasterworld (from the all-knowing jdMorgan) which seems to produce the behaviour you're after (404 on non-existent content):

#jdMorgan, again
#http://www.webmasterworld.com/apache/3906038.htm

# If the request is not for the the main domain or the www subdomain
rewriteCond %{HTTP_HOST} !^(www\.)?foo\.com
# get the requested subdomain name into variable %2
rewriteCond %{HTTP_HOST} ^(www\.)?([^.]+)\.foo\.com
# and if not already rewritten to subdomain's subdirectory
rewriteCond $1 !^subdomains/
# internally rewrite to prefix "/subdomains/<subdomain-name>/" to the client-requested URL-path
rewriteRule ^(.*)$ /subdomains/%2/$1 [L]

If files exist in /subdomains/bar, and I navigate to http://bar.foo.com, the content displays. If I navigate to http://baz.foo.com, I get a 404 Not Found (and an additional informational 404, as I've not specified the ErrorDocument) - this also appears in the error_log.

Is this what you're after? Using this allows you to see the unavailable content in the error_log, or indeed create a 404 page solely for capturing the 404ed requests and logging them.

(Again, you have jdMorgan on WMW to thank for this, not me. That man really is a fount of knowledge!)