Wildcard Subdomains with Dnsmasq
September 20, 2013
I’ve found Tim Pope’s post particularly useful. Basically, he has set up a domain name that resolves to locahost/127.0.0.1. This save you from having to specify subdomains in you /etc/hosts file - which is a hassle!
I’d like to offer another alternative using Dnsmasq. With Dnsmasq, you can set up a simple DNS server locally, then you can use an apache virtual host to deal with wildcard domains.
First, install Dnsmasq - I’m using Ubuntu (sorry for those who aren’t).
sudo apt-get install dnsmasq
Now, edit the /etc/dnsmasq.conf file:
# Add domains which you want to force to an IP address here. # The example below send any host in doubleclick.net to a local # webserver. address=/blah.localhost/127.0.0.1 # Or which to listen on by address (remember to include 127.0.0.1 if # you use this.) listen-address=127.0.0.1
The listen-address basically defines what IP address Dnsmasq will listen on. In our case this is your local machine.
The address line specifies a lookup for the name blah.localhost. As you can see, this is mapped to your local machine also.
Believe it or not, that’s pretty much it! And if you’ve tried to use Bind for a similar job, you’ll be very happy right now.
One more thing though! You need to add 127.0.0.1 as DNS server in your network settings. If you’re using linux, edit /etc/resolv.conf and add a new nameserver line to the top:
# Generated by NetworkManager nameserver 127.0.0.1 # <--- ADD THIS nameserver 220.127.116.11 nameserver 18.104.22.168
Finally, restart Dnsmasq:-
sudo /etc/init.d/dnsmasq restart
Now all you need to do is set up a virtual host:
<VirtualHost *:80> ServerName blah.localhost ServerAlias *.blah.localhost DocumentRoot /var/www/blah/current/public </VirtualHost>
Restart apache and you’re done.
Or! If you’re Using Rails
If you’re using Rails, you won’t need to set up a virtual host in Apache. Just start your server:
Then browse to the domain you set up:
Also, on a seperate note… You may notice internet pages are loading faster. This is because you now have a local DNS server cache. Therefore, resolving domains is a lot faster. You get this as a free side effect.