Quickly Editing the Hosts file on MacOS
Editing the hosts file is useful for all sorts of things! Here's a quick and easy guide to editing your hosts file on MacOS Sierra, High Sierra and Mojave.
Editing the hosts file is useful for all sorts of things, but if you're here and reading this article then I suspect I don't need to explain to you just why it's useful.
As simple a task as it is, because I do it so infrequently, I always end up Googling for a quick hint 🤦🏻♂️ - thus, my inspiration for this article! I mean, if I'm gonna read someone's blog, it may as well be my own, right?
The first step is to open up terminal which lives in the Utilities folder which you'll find within your Applications folder.
From here, you'll want to open up the hosts file with your favourite shell-based text editor as follows:
sudo nano /etc/hosts
After entering your password, you'll be presented with the hosts file, which may only have the top 10-or-so lines in it if you've never done this before.
You can add new entries by specifying an IP address (IPv4/IPv6) and a domain/domains. Lines that start with
# are ignored, which is a good way to quickly disable rules or to write comments so to make the file more readable for future you.
I've been rather crafty and have used my hosts file to block certain takeaway food websites that I used to be tempted by in the past and have rerouted their domains to localhost addresses. Turns out, editing the hosts file is just enough of a hassle to keep me from ordering pizza!
If you are planning on using the hosts file for site blocking, make sure to add an entry for IPv6 as well as good old IPv4.
With your edits made, hit
Y when prompted to save and
Enter when asked for a file name. Congratulations, your hosts file is now edited!
Flush DNS Cache
The final step you need to take is to flush out the DNS cache on your Mac. The cache has priority over the hosts file, so any changes you make to the host file might not start working for a while unless you flush out the old cache entries.
This can be done easily in Terminal by killing the DNS process which will force it to restart (with an empty cache).
sudo killall mDNSResponder
And with that, you should be good to go!
Thanks to Suzukii Xingfu for the awesome cover photo!