The Hosts file is used to map human-friendly domain names to numerical IP addresses. When a web browser is directed to a domain name, the system will check the Hosts file for matching records first, and if nothing is found, it will use the DNS servers to resolve the IP. Editing the Hosts file is a way for overriding DNS settings, and can be very useful for web development, or blocking a harmful domain. On Mac OS X, the Hosts file is used in much the same way as other operating systems. The difference is file location, and method of editing.
The Hosts file is located at:
It’s very easy to edit Hosts if you are somewhat comfortable with working command line in the Terminal. In this tutorial, I will map example.com to 192.168.1.130.
- Open the Terminal. It’s located at /Applications/Utilities/Terminal.app
- Enter the following command:
sudo nano /private/etc/hosts
- This command is using nano, the built-in command line editor to open the Hosts file. You will be asked for your password because root privileges are needed to edit the Hosts.
- You will now see the contents of the Hosts file. It has one entry per line, with the hostname followed by the IP address. Hashed lines (#) are comment lines and are ignored by the system. Use the arrow keys to move the cursor.
- Append your entries to the end of the file. Use tab key or spaces to separate the IP from domains. Like so:
- Check you entries, and Save the file by pressing Control + O keys. (letter O, not zero) It will ask where to write, with the Hosts file already typed, press Enter to write.
- Control + X to close nano editor.
- Now for your new entry to take effect, the DNS cache needs to be flushed.
OS X 10.5 or later use this command:
OS X 10.4 or earlier use:
That’s it! You’ve added entries to your Hosts file, go ahead and reload your web browser to see the results.
Similarly, it’s possible to block a harmful domain by mapping it to the localhost. Thereby preventing the computer from reaching the domain. In this situation, map the bad domain to 127.0.0.1. It will not be able to connect.
The above instructions will work on Mac OS X 10.2 and above. If you’re dealing with an older system refer to this page of Apple’s documentation.