Block Websites with /etc/hosts File

Here's how to block websites by editing your /etc/hosts file.

/etc/hosts is a file where you can make custom DNS (domain name server) entries. In other words, point this name (domain/url) to this IP address. Without a functioning DNS server, typing a url into a browser address bar won't connect to the server IP of the website.

When we want to block access to a website, we break that connection by pointing certain domains to 127.0.0.1. This is a valid IP address, and it always mean localhost, or this computer. And unless you're running something on port 80 of localhost, requests to these mapped domains will fail.

First, open the file with sudo permissions:

sudo $(which nvim) /etc/hosts

Then add your edits. For instance, try, just try, to block YouTube:

127.0.0.1       youtube.com
127.0.0.1       www.youtube.com
127.0.0.1       youtu.be
127.0.0.1       www.youtu.be
127.0.0.1       youtube-nocookie.com
127.0.0.1       www.youtube-nocookie.com
127.0.0.1       m.youtube.com

Save and exit. Then go to your browser and load the domain, and it should fail:

xdg-open youtube.com

And your pings should go to 127.0.0.1:

ping youtube.com
PING youtube.com (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.045 ms

If you're still able to access the site, you may need to either flush your OS-level DNS cache:

sudo resolvectl flush-caches

(This assumes that you're using systemd-resolved. To find out otherwise, you could run sudo lsof -i :53, where 53 is the default DNS server port.)

Or, in my case, you have to really want it:

sudo reboot

And when you come back to youtube.com, it'll still show up, but with no videos. This is because it's running a service worker. You can go into devtools and unregister the sw.js for the final step.

How else do you block sites?