Simple local web development with Apache and Dnsmasq
When you sit down and start work on a new project, what hoops do you have to jump through before you get your app running in your browser? There are more than likely always going to be two; creating a spoof domain that you create in
/etc/hosts so that you can access your app, and then a virtual host in Apache to make your files accessible. And it sucks having to do this each time. Don’t you wish you could just get on with the project as soon as you think of it? Read on.
This was all inspired by Pow, a zero-configuration rack server created by 37signals, that allows Rails developers to do exactly that. By following convention over configuration, this can all be easily achieved. If you’re happy with accessing your apps via a spoof domain ending in
.dev, then follow these steps.
I’m assuming that you’ve got Homebrew installed, and that you’re using the built-in version of Apache on Mac OS X 10.6 Snow Leopard. However, these instructions should work fine on Linux too.
Dnsmasq is a simple to install and setup mini DNS server. We’ll use it to setup a wildcard record of anything
.dev to point to your local machine.
brew install dnsmasq
Follow the instructions after install about copying the configuration file to the expected place in
/usr/local/etc/dnsmasq, but don’t copy the
launchd settings yet. First of all edit
/usr/local/etc/dnsmasq and add the following at the very bottom:
Save. Now copy the
launchd settings across. Dnsmasq should now be running. You now need to tell your system to use it as a DNS server.
Open up System Preferences and go to your Network settings and the DNS servers. Add
127.0.0.1 to the top of the list, and then add whatever your normal internet facing DNS servers are beneath. I use OpenDNS. My DNS server list then looks like:
Apply changes. Now open the Terminal and run a ping on anything ending with a
It should start pinging your machine,
127.0.0.1 - if it does, all is good.
Now we can move onto configuring Apache for the last time.
Edit the following file, substituting
yourusername with whatever your system username is:
sudo nano /etc/apache2/users/yourusername.conf
And then make it look like the following, again replacing
Options Indexes MultiViews FollowSymLinks Includes
Allow from all
Save. And then run
sudo apachectl graceful. This will restart Apache. In the above configuration, we’re using Apache’s mod_vhost_alias module to dynamically configure virtual hosts and document roots on the fly.
Testing it all works
mkdir -p ~/Sites/test.dev/public
echo "test.dev" > ~/Sites/test.dev/public/index.html
Now visit http://test.dev/ in your web browser. Hopefully you should see
test.dev - if so congratulations; you’re going to save so much time in the future now.