How to Edit the Hosts File in Mac OS X with Terminal
The hosts file in Mac OS X is stored at /private/etc/hosts but can also be accessed at the more traditional location of /etc/hosts. If you’re looking to edit hosts, you’ll want to target the file located in /private/etc/ though.
We’ll walk through how to manually edit the hosts file in OS X Lion and OS X Mountain Lion with the command line using the simple text editor called nano. If you’d prefer to avoid the Terminal, you could try the easier method of using a preference pane.
- Launch Terminal , found in /Applications/Utilities/ or launched through Spotlight
- Type the following command at the prompt:
- Enter the administrator password when requested, you will not see it typed on screen as usual with the command line
- Once the hosts file is loaded within nano, use the arrow keys to navigate to the bottom of the hosts file to make your modifications
- When finished, hit Control+O followed by ENTER/RETURN to save changes to /private/etc/hosts, then hit Control+X to exit out of nano
- Quit out of Terminal when finished
sudo nano /private/etc/hosts
You can verify your hosts modifications immediately with ping, Safari, or any other network app. Changes take effect immediately though some adjustments may need to be accompanied by a DNS flush.
If you’d like to see how this entire process is accomplished before doing it yourself, watch the video below to see a demonstration of the hosts file being modified on OS X Mountain Lion to block the website ‘yahoo.com’ from loading:
Note: the procedure is the same with older versions of Mac OS X, though the path to hosts could be /etc/hosts.
Tips to Consider When Editing Hosts Files
The following tips go beyond OS X and apply to any hosts file, be it on a Mac, Windows, or Linux.
- The preceding IP address is where the following domain will resolve to
- Always add new hosts to their own unique line
- The # symbol functions as a comment, it can be used to add comments to hosts entries or to comment out hosts modifications
- You can block websites through hosts by adding them to the file and sending them nowhere, preventing access
- You can redirect websites locally using the same logic, perfect for setting up test domains
- With some modifications, it can be necessary to flush DNS cache with dscacheutil before the changes take effect
- For juggling multiple hosts files consider using a manager app like GasMask
- If the hosts file claims to be locked, it’s because you did not prefix the edit with the “sudo” command
Let us know in the comments if you have any questions or tips.