Edit hosts file to block websites [Mac OS X]

The hosts file is used to map domains to IP addresses (at a primary level, above DNS servers). When a URL is requested, the system checks for a mapping on the hosts file first and gets the corresponding IP address. Only when it does not find an entry does it resolve the IP with the help of global DNS servers.

Thus, the hosts file has maximum priority, and you can edit it to block certain domains (known malicious domains), or to redirect domains to local addresses (for web development and testing).

Edit hosts file – Mac

To edit the hosts file in Mac OS X, you have to use the terminal to open the file (since it is a system file). But do not flinch upon hearing “terminal” – it is easy since we have detailed instructions and screenshots below.

Step 1:
Open Terminal from Applications -> Utilities -> Terminal.app, or by typing the first few letters in Spotlight.

Step 2:

Type the command below into the terminal to open hosts file in ‘nano’ text editor:

sudo nano /private/etc/hosts

Type in your Mac OS X account password when asked, then hit enter.

Step 3:
The hosts file contains some built-in mappings like 127.0.0.1 – localhost.

Warning: Do not edit the built-in lines, they are important for your computer to function properly!

‘nano’ is a command-line editor, which means that you have to use solely the keyboard to edit the file. Press the down arrow key to get below the default rules, then add new rules.

Block domains with hosts file

To block a domain, use the following syntax (where domain.com is to be blocked):

0.0.0.0 domain.com

Redirect domains with hosts file

To redirect a domain, use the following syntax (where domain.com is to be redirected to 154.0.0.1):

154.0.0.1 domain.com

Once host file editing is done, press Control + O to save the file, then hit enter, then Control + X to close the hosts file.

Step 4:

The last step is to flush your local DNS cache. In terminal, enter the command below:

dscacheutil -flushcache

Do you use an older version of Mac OS? Here is how to flush DNS cache in Mac OS X Tiger.

This step is important! The hosts file edits will take effect only after this step.

Leave a Reply

© Techzilo 2020 All Rights Reserved.

preloader