Handling subdomains for Rails in your development environment

Written by on

We built Tula with subdomains from the beginning, so we needed a nice way to handle subdomains in our development environments. We used pow for some time, but that wasn't the perfect solution for me. That's because I wanted a few things out of a solution: 

  • Configure it once and forget about it
  • Know exactly when my server was started and stopped
  • Use whatever I wanted as an app server i.e. unicorn

It took us awhile to settle on this solution, so here it is. It uses a combination of Apache (or nginx) and dnsmasq which I've become a huge fan of. 

The first part is simple. You'll want to install and use dnsmasq. It's a nice, lightweight and local DNS provider that will run on your machine. You can serve the names of local machines which are not part of the global DNS. 

It's easy to install on both Linux and Mac. 

# On Ubuntu Linux
sudo apt-get install dnsmasq

# On Mac with Homebrew
brew install dnsmasq

Once installed, you'll want to add the following to your dnsmasq.conf file. This will resolve any domain with a TLD of .dev to your local machine. This is handy if you have a lot of projects (Rails or otherwise) in the same directory. 

Next, you'll want to configure Apache (or nginx) as the following. The key for Apache is VirtualDocumentRoot. It allows you to set the document root based on various parts of the domain name. In this case, I've taken the main part of the domain name as the document root. The domain name will resolve to a project in my Projects directory. This will always work if I continue to use my Projects directory for Rails projects.

If you set this up once for your Rails projects, you'll never have to worry about adding anything to your hosts file, nor will you have to worry about port numbers. It's all taken care of for you.  You can access your subdomains as you would normally. It's important to note that unicorn is running on port 5000 in this example.