maetl

Running multiple hosts on OS X

The process is just as straightforward on OS X as it is on Windows - if you do things manually. The catch for me was that I needed to set up a script to automate the process.

Normally, OS X expects you to use the NetInfo Manager (found in Applications/Utilities), but it's much easier to add a new entry to the hosts file at /etc/hosts. The problem I ran into was that OS X doesn't care about /etc/hosts unless you tell it to.

Instead of doing what I expected would work:

# add new hosts entry
File.open("/etc/hosts", "a") do |hosts|
  hosts.puts "127.0.0.1  #{new_host_name} "
end

# reload hosts file into netinfo database
`niload hosts . < /etc/hosts`

NetInfo actually expects more properties than are found in the standard hosts format. I found that using the niutil command works much better:

# add a new host entry
`nituil -create . /machines/#{new_host_name}`

# add IP property pointing to loopback address
`nituil -createprop . /machines/#{new_host_name} ip_address 127.0.0.1`

# add NetInfo specific 'serves' property
`nituil -createprop . /machines/#{new_host_name} serves ./local`

It seems that without the ip_address and serves properties, the NetInfo database doesn't register the host. There may be other ways of doing this, that do involve the traditional style of /etc/hosts entries - however I found that bypassing this and using niutil directly was more effective.

Hint: these examples are shown in Ruby, not as pure shell commands. I recommend rolling them into a Rake task (or Python/Perl/shell script) if you create a lot of different websites and want to speed up the process of setting up new virtual hosts. Mileage may vary.

This Note