How to Block Websites Using Ubuntu Hosts File?

Editing the hosts file in Ubuntu is a straightforward and powerful way to block access to specific websites across your entire system without needing third-party software. By mapping a website’s domain name to a local, non-routing IP address, your system will fail to connect to the site, effectively blocking it. This guide provides a step-by-step walkthrough on how to locate, edit, and save the hosts file using the terminal, along with how to test and revert your changes.

Step 1: Open the Terminal

Because the hosts file is a critical system file, you need administrative privileges to modify it. Start by opening your terminal. You can do this quickly by pressing Ctrl + Alt + T on your keyboard.

Step 2: Open the Hosts File with Nano

To edit the file, use a command-line text editor like Nano coupled with sudo to grant temporary root privileges. Type the following command and press Enter:

sudo nano /etc/hosts

You will be prompted to enter your Ubuntu user password. Note that no characters will display on the screen while you type your password; this is a standard security feature. Type it out and hit Enter.

Step 3: Add the Blocklist Entries

Once the file opens in the Nano editor, use the arrow keys to scroll down to the very bottom of the file. Do not alter or delete any of the existing lines, as they are essential for your system’s network functionality.

To block a website, you need to redirect its URL to the local loopback address, which is 127.0.0.1. Add a new line at the bottom using the following format:

127.0.0.1 example.com 127.0.0.1 www.example.com

Note: It is best practice to add both the root domain (example.com) and the “www” subdomain (www.example.com) to ensure the website is completely blocked across different browsing habits.

Step 4: Save and Exit

After adding the websites you wish to restrict, you need to save your modifications:

Step 5: Flush the DNS Cache (Optional)

Ubuntu generally registers changes to the hosts file immediately. However, if you find that the websites are still accessible in your browser, your system or browser might be caching old DNS data. You can force Ubuntu to clear its network cache by restarting the system systemd-resolved service with this command:

sudo systemctl restart systemd-resolved

How to Unblock the Websites

If you ever need to restore access to the blocked websites, simply reopen the file using sudo nano /etc/hosts, navigate to the bottom, and delete the lines you added. Save and exit the file, and the websites will be instantly accessible again.