Wildcard subdomains of localhost

10 February 2011
Update: The xip.io service from 37 Signals pretty much obviates the below; unless you're looking for a solution that works offline in which case it might still prove useful.

It always slightly niggled that I couldn’t just stick a *.localhost entry in /etc/hosts and have all subdomains of localhost resolve to But setting up a local nameserver, and making sure external domains still got resolved properly, always seemed like too much faff. It turns out though, thanks to dnsmasq, that it’s actually very straightforward. (Instructions are for Ubuntu but dnsmasq runs on most *nix systems.)

1. Install dnsmasq, a DNS forwarder which you can configure to reply to certain queries locally and forward all others on to your external nameservers:

sudo aptitude install dnsmasq

2. Configure it to resolve all localhost domains to By default, dnsmasq will include all files in /etc/dnsmasq.d/ so create a new file here with a sensible name like /etc/dnsmasq.d/localhost.conf and add the following line:


(Hopefully the syntax is obvious here. See the man page for more detail.)

3. You now have a DNS forwarder up and running on localhost. The final step is to get your resolver to send queries to it. We do this by getting our DHCP client to add the local address to the list of nameservers it gets from the DHCP server. So edit /etc/dhcp3/dhclient.conf and add the following line:

prepend domain-name-servers;

(You’ll probably find that this line is already there and you just need to uncomment it.)

4. To check everything’s working, reload the dnsmasq config and request a new lease from your DHCP server:

sudo service dnsmasq restart
sudo dhclient

And you should be good to go…

dig somesubdomain.localhost
comments powered by Disqus