DEV Community

Locahl
Locahl

Posted on

How to block websites with the hosts file

You can block a domain on your machine without installing another browser extension.

Point the hostname at a dead address in the hosts file. The OS resolves it locally and the site never loads.

This is blunt. It works for distraction sites, telemetry hosts you do not need, and quick local tests.

The pattern

0.0.0.0   www.example.com
0.0.0.0   example.com
Enter fullscreen mode Exit fullscreen mode

0.0.0.0 is the usual choice. Some people use 127.0.0.1. Both stop the real site from loading. 0.0.0.0 avoids sending traffic to a local server you might already run.

Block both apex and www if the site uses both.

macOS and Linux

Edit hosts:

sudo nano /etc/hosts
Enter fullscreen mode Exit fullscreen mode

Add your lines, save, then flush DNS:

# macOS
sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder

# Linux (systemd-resolved)
sudo resolvectl flush-caches
Enter fullscreen mode Exit fullscreen mode

Windows

Open Notepad as Administrator, open:

C:\Windows\System32\drivers\etc\hosts
Enter fullscreen mode Exit fullscreen mode

Add the same style of lines, save, then:

ipconfig /flushdns
Enter fullscreen mode Exit fullscreen mode

Verify

ping -c 1 www.example.com
Enter fullscreen mode Exit fullscreen mode

You should see 0.0.0.0 or a failed route, not the real public IP.

Browser still loading the site? Quit it fully and reopen. Chrome also has its own DNS cache under chrome://net-internals/#dns.

What this does not block

  • Apps that hardcode IPs
  • Sites reached through a VPN or proxy that ignores your hosts file
  • HTTPS hosts you only blocked under the wrong name (example.com vs www vs a CDN host)
  • Mobile apps on another device (hosts is local to that machine)

For team-wide or network-wide blocking you need DNS or firewall rules, not a laptop hosts file.

Keep it tidy

Group blocks under a comment:

# focus mode
0.0.0.0   www.reddit.com
0.0.0.0   reddit.com
0.0.0.0   www.youtube.com
0.0.0.0   youtube.com
Enter fullscreen mode Exit fullscreen mode

When you need the site again, comment the lines or delete them and flush DNS.

Safety note

Do not block domains your OS or package manager needs unless you know what you are doing. A bad block looks like "the internet is broken" until you remember last night's edit.

Start with one domain, verify, then add more.


If you switch hosts a lot, a small desktop manager helps keep profiles and DNS flush in one place: Locahl.

Top comments (0)