/etc/hosts – The hosts file


The other day I decided to set up my iBook so that I can do web development on it.

While setting up my new server, I was moving a domain name to the new server, but didn’t want to actually change the DNS for the domain until I knew Apache was configured properly. I needed some way to test Apache’s virtual host configuration without actually making the DNS change. Turns out, since OS X is based on UNIX, you can add dns entries to your computer manually.

Edit the file /etc/hosts, and include the name and IP address for the host you want to add. For example:

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
123.123.123.123 domainname.com

You’ll need to do this with root privileges, since it is a system file. You’ll have to do something like

sudo vi /etc/hosts

Update: In OS X 10.5 it is no longer necessary to reload the hosts file. It will happen automatically.
After you save the file, you’ll need to get OS X to refresh its hosts database.

sudo niload -v -m hosts . < /etc/hosts

After that, you should be all set! Your computer will resolve dommainname.com to 123.123.123.123 without contacting any DNS servers.

Note, this is not an OSX-specific feature. Windows also has a hosts file. It is usually located at:

c:\windows\system32\drivers\etc\hosts

To get Windows to recognize the changes, you need to flush the DNS.

ipconfig /flushdns

You can also read about the hosts file on Wikipedia.

  1. No comments yet.
(will not be published)