How to edit your hosts file, and why you might want to? (mac edition)

JW
3 min readAug 5, 2020

Today at work I needed to change my host file to map a certain ip address to a url.

I thought I would document up the steps I took to do this and why the heck you would want to do this.

What is a Hosts file do?

To understand this, we first need to talk quickly about some web basics.

When you navigate to a url in your web browser eg. https://google.com, this is actually navigating to an ip address, a series of numbers separated by dots. The Domain Name System (‘DNS’) maps the ip addresses to urls that is more human friendly.

Your hosts file is a local file on your mac that can be used to override the default DNS mapping.

So why change your hosts file?

There are many reasons but I will explore two here briefly

1. Mapping for development

When developing you may want to test out your local implementation. You may have deployed an implementation and want to test that everything is working fine before doing the actual DNS mapping to your web url. You can then map the prospective url eg “https://www.this-is-the-best-website-ever.com” to the ip address your implementation has been deployed to (disclaimer: website url for demonstrative purposes only).

This is the reason I was altering the hosts file.

2. Block a website

Well, let’s say you really hate a website because its wasting your time or worse (not pointing any fingers here). Mapping the url to 0.0.0.0 blocks access to the website.

Step by step guide

Note: you are going to need admin access and remember your system password.

1. Step one: Open up the hosts file

You can do this by opening up your Terminal and opening the hosts file located at /etc/hosts with nano or your favourite text editor.

sudo code /etc/hosts

I’m going to use VSC (I am assuming if you are too then you already added the ‘code’ command to the PATH).

2. Step two: Gain admin access

You should be faced with the following:

Enter your admin password.

3. Step three: Add/edit ip-to-url map entry

Cool so now you’re in.

You should have a file open similar to the following:

I’m going to block two certain time-consuming websites:

0.0.0.0    www.youtube.com
0.0.0.0. www.facebook.com

You can just as easily add a map instead:

31.13.71.1   www.pretending-to-be-a-facebook-dev.com

So my amended hosts file looks as follows:

4. Test if it works

Try navigating to the websites that we blocked

It is a pretty easy thing to once you do it and can definitely be handy.

Hope this helps!

--

--

JW

Software Engineer, and avid learner of history.