How to edit the Hosts file on a Mac

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:

/private/etc/hosts

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.

  1. Open the Terminal. It’s located at /Applications/Utilities/Terminal.app
  2. Enter the following command:
    sudo nano /private/etc/hosts
  3. 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.
  4. 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.
  5. Append your entries to the end of the file. Use tab key or spaces to separate the IP from domains. Like so:
  6. 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.
  7. Control + X to close nano editor.
  8. Now for your new entry to take effect, the DNS cache needs to be flushed.
    OS X 10.5 or later use this command:

    dscacheutil -flushcache

    OS X 10.4 or earlier use:

    lookupd -flushcache

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.

More great mac tips:


This entry was posted in Guides and tagged , , , , . Bookmark the permalink.

Comments are closed.