28

How to Edit the Hosts File on macOS (Mac OS X)

Posted by Jim Tanous on September 23, 2019
Edit Hosts File OS X

Your Mac’s hosts file is a small, but important text document that has the ability to map hostnames to specified IP addresses. Although the modern Internet uses a variety of public and private DNS servers to map IP addresses, the hosts file is a handy way to override those DNS servers, allowing you to manually point a website address to a desired IP address, or block access to a site altogether by pointing to an unused or internal IP address.

Here’s how to edit the Mac hosts file on macOS (previously known as Mac OS X).

Edit Your Mac Hosts File with Text Edit

There are two primary ways to edit the hosts file in Mac OS X. The first is by using TextEdit, since the hosts file is merely a simple plain text document. However, you can’t open the file directly, since it resides in a protected area of the file system. Instead, we need to copy the file to an unprotected location, like the Desktop, edit it, and then copy it back.

To find the hosts file, open the finder which you can access by clicking on the desktop or on the smiley face finder in the lower left of your screen, then follow these steps:

  1. Select the Go pull-down menu
  2. Then select Go to Folder from the menu
  3. In the box, enter /private/etc/hosts into the box
  4. Press ReturnEdit Mac Hosts File OS X
  5. A new Finder window will open and your Mac’s hosts file will be selected, click and drag it out of the Finder window and drop it on your desktop.

This will let us freely edit the hosts file.
Change Mac Hosts File OS X
To open it, simply double-click and it will display the file’s contents in TextEdit (or the text editor of your choice).

By default, the /etc/hosts file is relatively simple. It contains a number of lines of descriptive text which are “commented out” with the pound or number (also called a pound or hashtag) sign (#).

Any line that starts with a # sign is a comment and is not read by the /etc/hosts file. So comments are how you can add notes to your hosts file and comment out any lines that you want the /etc/hosts file to stop reading as entries but do not want to delete in case you need them in the future.

For each line, any text after the pound sign is ignored by the computer, making it a good way to add notes and descriptions to your files. It also contains default IP values for localhost and broadcasthost. To edit the file, you’ll add your own lines after broadcasthost.
Modify Hosts File Mac OS XIn addition to testing newly developed websites and web hosting migrations, another reason to edit the hosts file is to block access to specific websites.

In our example, we’ll pretend that the computer we’re using is a work system that we want to use exclusively for work, not allowing ourselves to get distracted by Facebook on our work machine.

To do this, type the IP address you wish to assign followed by a hostname. In our case, we want to block Facebook so we’ll map www.facebook.com to 0.0.0.0 which, as an invalid IP address, will result in an error.

Now, whenever we try to go to www.facebook.com from our Mac, the Web browser will fail to load the page, hopefully encouraging us to get back to work!
Edit Hosts File OS XAlternatively, you can enter the IP address of a valid site instead of 0.0.0.0, which will result in users attempting to access Facebook being directed to the site of your choosing.

To determine a website’s IP address, you can use the dig command, which comes standard with macOS. To “dig” the site via Terminal, we simply open up Terminal and then run the dig command on URL, which will then return the IP address as output.

$ dig www.techjunkie.com +short
104.25.27.105
Note: The +short option keeps the output to just the information we need, which is the IP address.

Make note of the IP address that’s returned and use it in your Mac hosts file mapping. For example, The New York Times website at www.nytimes.com returns an IP address of 170.149.172.130. If we map that to Facebook in our hosts file, any time someone using the Mac tries to go to Facebook, they’ll see The New York Times load instead.

Note: Many websites won’t allow you to map a domain name to the IP address currently mapped to the site so you’ll get a security error when you try.
Edit Hosts File OS X
You can add as many entries to the hosts file as you wish by entering new mappings on each line. Once you’ve made your desired changes to the hosts file, save it in its current location on the Desktop.

Then, drag and drop the hosts file from your Desktop back to its original location at /private/etc. If you’ve closed the Finder window pointing to this directory, simply use the Finder > Go > Go to Folder command, discussed above, to reopen it.

When you drop the hosts file back in its original location, macOS will ask you what to do about the unmodified hosts file that’s already there. Choose “Replace” and then enter your administrative user password to authenticate the transfer.

With the modified hosts file now in place, fire up your Web browser to test the changes.

In most cases, the new mapping should work immediately, but if you’re not seeing the correct behavior, you may need to flush your DNS cache, forcing the browser to read from your hosts file to determine the mapping.

To flush the DNS cache on your Mac, open Terminal and use the following command (sudo enables you to run this command as the admin of your machine):

$ sudo killall -HUP mDNSResponder
Note: You will need to enter your admin password to execute this command.

To get your Mac to clear your DNS cache, then confirm it’s cleared your cache by echoing a confirmation, enter these two commands separated by a semi-colon as shown here:

$ sudo killall -HUP mDNSResponder;say DNS cache has been flushed

Edit Your Mac Hosts File In Terminal With Nano

The steps in the previous section are easy enough, but if you want to avoid copying the hosts file you can edit it directly in Terminal using the UNIX Nano Text Editor, which is built into macOS.

To get started, launch Terminal, type the following command, and press Return. As with all sudo commands, you’ll need to also enter your admin password to execute it:
$ sudo nano /private/etc/hosts

You’ll now see the hosts file open in the Nano editor or vim or another editor of your choice. To navigate and edit the file in Nano, use the arrow keys on your keyboard.
Edit Hosts File Nano
Just as we did with the TextEdit method, above, we can add, edit, or remove hostname mappings at will. Because we launched Nano using sudo, any changes will be authenticated and saved directly to the original hosts file, without the need to copy it outside of its home directory.

When you’re done making changes, press Control-X to exit the editor, Y to save, and Return to overwrite the existing hosts file.

As we mentioned earlier, make sure to flush your DNS cache if you notice that your new mappings aren’t working properly.

Our examples mentioned blocking and redirecting distracting sites in a work environment but you can also use these steps to manually block access to malicious websites and, of course, other uses as well.

If you ever make a mistake and you’re not sure how to fix it, you can always restore the default hosts file contents by using one of the methods above to enter the following default information:

##
# 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
fe80::1%lo0 localhost

If you are a Mac user and found this article useful, you might want to check out other TechJunkie tutorials, including How to Find Your Mac’s Exact CPU Model and How To Flush the DNS in Mac Mojave.

What’s the reason you are seeking to edit your Mac’s hosts file? How did it work out? Please tell us about it in the comments below!

28 thoughts on “How to Edit the Hosts File on macOS (Mac OS X)”

Artur Sá Menezes says:
About permitions, using a common Text Editor:
— Edit;
— When warning appears about permitions, save as a COPY to your Documents folder;
— Copy (drag’n drop) the hosts file to “/private/etc/hosts” overrighting;
— Type the requested password (system admin/superuser).
That is all, folks @@)
Reply
SassyLou says:
How do you use this to block IP addresses from OUTSIDE your network..from the internet?
Ping attacks..etc.
Reply
Aier.amiyoyo.h Huang says:
Thanks!
Reply
Gold Luna says:
Thanks
Reply
Vincent Cardona says:
thanks!
Reply
Erick Wendell says:
Thanks!!
Reply
Cristian Nica says:
Thanks!
Reply
Bart says:
To block facebook? For pranks? Serious?
Come on, us developers use it to mock production environment for our apps running on localhost ofcourse.
Reply
Anjospot says:
Works for El Capitan. Thanks.
Reply
Me says:
Exceedingly helpful and easy to follow. Thanks for the assistance.
Reply
Aravind Kumar Yadav says:
thanks
Reply
Micky says:
Just found the service https://hosts.cx . I find it much easier.
Reply
Will Loury says:
Thank you very much
Reply
Matthew Waring says:
The tip about drop to desktop, edit and back is great 🙂 thanks for the article.
Reply
Rusty says:
This does not seem to work at all on Yosemite 🙁
I have changed the host file etc and used the following to clear the caches
‘alias clearcaches=’sudo discoveryutil mdnsflushcache;sudo discoveryutil udnsflushcaches;say flushed’
when i ping the site it gives what is written in the hosts file – but when I go to it in a browser (chrome, safari, chrome canary) it does not use the address from the host file 🙁
I am at my wits end…!
Reply
Chris W says:
Check if you have http://www.xyz.com as well as xyz.com added to hosts. (seems to make a difference sometimes)
Reply
Danilo Salguero says:
Awesome article – thank you Jim. *Thumbs up*
Reply
Marco Aurélio Rodrigues says:
Thanks for the post. That’s exactly what I needed.
Reply
Andrea Williams says:
Thanks for the super easy to follow instructions! Very helpful.
Reply
SojournerWeb Studio says:
This is a great tool for checking websites being transferred to a different server.
Reply
Mtb4ever says:
excellent, thank you so so much!
Reply
bwrightson says:
Works, thanks!
Reply
Gary says:
Great instructions but I have one issue. When I copy the edited host file back into the “etc folder” it doesn’t ask me to replace. It says to “Authenticate”. After I authenticate it doesn’t request user name and password and nothing happens. The host file remains in its original form. I am running OSX Mavericks.
Reply
Arnold Watson says:
The instructions here were AWESOME and had everything I needed to accomplish my task. Thank you!
Reply
netsi1964 says:
This is great! Thank you.
I would like to recommend this page “Ad server hostnames for blocking ads (format: hosts — in hosts file format)” on http://pgl.yoyo.org/adservers/ which is keeping track of many of the advertisement hostnames. It can be a little tricky to find the correct format file, as the service offers lists in a lot of different formats. This one works for me on my OSX Mavericks mac mini: http://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=0&startdate%5Bday%5D=&startdate%5Bmonth%5D=&startdate%5Byear%5D=
When you paste the list into your hosts you maps any request to host to “localhost” (127.0.0.1) efficiently disabling “any”/many of the annoying advertisements shown on many sites 🙂
Reply
Tom says:
Hi, none of this works for me. In fact, ever since I started running the “dscacheutil -flushcache” command, blocking no longer works. I am on mavericks, so I thought the addtion of the second command would save the day, but doesn’t work either. It doesn’t matter if I restart the browser or computer. Nothing works. Is there a reason for this? Have they changed something in Mavericks we’re not looking at?
Reply
Scott says:
For anyone else who has locked file problem, I found the answer here: http://superuser.com/questions/40749/command-to-unlock-locked-files-on-os-x
Thanks for this page and the suggestions!
Reply
Scott says:
Ok, I tried both of those but when I try the first one (I’m using OSX mavericks) I’m getting this error on dropping the hosts file back in:
“The Finder can’t complete the operation because some data in “hosts” can’t be read or written.
(Error code -36)”
On the second method, using Terminal, I get this at the end:
[ Error writing /private/etc/hosts: Operation not permitted ]
Any ideas? I had edited this file before and it worked great but that was before i “upgraded” to Mavericks
Reply
TekRevue says:
Sounds like something is using or locking the hosts file. I presume you’ve tried restarting, and making sure that no other apps are opened, but give that a shot if you haven’t.
Also, find the original host file, highlight it, press Command-I (or right-click Get Info) and make sure the “Locked” box is unchecked under General. Also, look under “Sharing & Permissions” and make sure your user account has Read & Write access.
Try those, and let me know. I’ll keep looking for other solutions.
Reply
TekRevue says:
Also, this knowledge base article from Apple points to Error Code -36 as possibly being related to a problem with your physical drive. Make sure you have backups of your data and consider running drive maintenance utilities to check the drive integrity.
http://support.apple.com/kb/HT2433?viewlocale=en_US&locale=en_US
Reply

Leave a Reply to Scott Cancel reply

Your email address will not be published. Required fields are marked *


Disclaimer: Some pages on this site may include an affiliate link. This does not effect our editorial in any way.