VirtualHost Hacking with Wildcard DNS

A recent topic in the webhosting business is wildcard DNS.  Setting up a wildcard record will allow you to essentially have infinite subdomains all pointing to the same place…. you can try this on my site if you’d like by typing in any random subdomain (like and then see if point back to my primary, unless it’s one that I’ve actually created.  Now if you combine this ‘technology’ with the power of .htaccess rewrites, then congratulations.  You’ve just cheated your host and obtained unlimited subdomains.

The first thing you would need to do is have a wildcard DNS record set up.  If you have access to your own zone files, that’s great, otherwise you’ll need to ask your host to set it up for you.  Fair warning though, your hosting company is not stupid (unless it’s Dreamhost) so don’t be surprised if they decline your request.  To set up the DNS zone you simple need to add an a-record “*” like so:

* 14400 IN A

*Note: Some argue that you need to use the full  * as the first field…this is actually not required at all, nor recommended!

Depending on your platform, you’ll likely find your domain’s zone file in /var/named/ unless you have this feature in your host’s control panel.  Once you’ve added the record simply reload named/BIND with the /etc/init.d/named reload command if needed.   If you’re using an interface it will probably do this for you automatically.

Now you need to add ServerAlias line to your httpd.conf for the wildcard, if your host does not already have Apache configured this way.  Inside the <virtualhost> tags for your domain, add this line:

ServerAlias *

Then restart Apache as usual (/etc/init.d/httpd restart) and test a random subdomain to see if it’s working.

So now you will notice that any non-distinguished subdomain shared the same document root as your primary….that’s great and all but it really serves no purpose, so that is where mod_rewrite comes in.  You can add and modify the follow code in your .htaccess to have Apache direct these subdomains to where they need to go:

RewriteEngine On
RewriteRule ^\.htaccess$ – [F]
RewriteCond %{HTTP_HOST} !^www\.example\.com?$
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com?$
RewriteRule ^$ /folder/page.html [L]

Using your imagination you can write your own script that can create subdomains and the appropriate .htaccess entries on-demand (assuming that this is not blocked by mod_security).  The end result is seemingly unlimited subdomains on your account!  Also, the changes are usually immediate and do not require propagation.


Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *