Configuring subdomains in development with lvh.me

3 comments

I do a lot of work with subdomains, managing them locally on my development and test machines has always been a bit of a pain. Going way back, I can remember manually editing the hosts file in system32\drivers\etc\ on Windows! On the Unix we have /etc/hosts.

Unfortunately /etc/hosts doesn’t allow wildcard definitions for subdomains, so you have to manually specify each one. For a while I used this simple bash script to append a new domain (or subdomain) to the /etc/hosts file;

#!/bin/bash

SUBDOMAIN=$1
TLD=$2

if [ $# -lt 1 ]
then
  echo "which subdomain?"
  read SUBDOMAIN
  if [ -n "$SUBDOMAIN" ]
  then
    SUBDOMAIN="$SUBDOMAIN."
  fi
fi

if [ $# -lt 2 ]
then
  echo "which tld?"
  read TLD
fi

echo "127.0.0.1 $SUBDOMAIN$TLD" >> /etc/hosts
echo "OK, added 127.0.0.1 $SUBDOMAIN$TLD to /etc/hosts"

Save this script as executable somewhere in your PATH, call it something like addhost then run it from anywhere like so;

> addhost # will prompt for subdomain, tld (leave blank for no subdomain)
> addhost www test.com

This soon became tiresome, with some apps requiring 10’s or 100’s of subdomains to be tested and available locally. So I took to writing a simple rake task that would automatically pull subdomain names from an applications database and append them to my local /etc/hosts file (here’s that script).

Time passed and my script worked well, but had a some disadvantages. I had to re-run it every-time my subdomain data changed, and across apps it required modified since I had different ways and means of defining subdomain sites.

Enter the most excellent suggestion from Tim Pope. Using DNS to solve this problem means no more hassle! He set up a localhost wildcard, pointing *.smackaho.st at 127.0.0.1. Essentially this means that [anything].smackaho.st will point to your local machine. Not happy with smackaho.st? lvh.me does the same thing (lvh, as in local virtual host). Or since most developers have a couple of old domains lying dormant, why not use one for this? I learned of Tim’s technique through the Subdomains in Rails 3 screen-cast from Ryan Bates.

So I think that wraps up all my posts on subdomains, whats that? four now!? Here are the other three.

January 10, 2011 17:54 by

3 comments so far

Leave a comment