
How to Block or Limit Website Access on Linux
This guide serves as a reference for those who want to block access to social media during working hours — without needing to configure firewalls, proxies, or other complex solutions. We'll use only a Bash script and Linux's task scheduler, cron
. If you prefer, you can watch the tutorial video available at the bottom of the page.
Requirements
- Linux Operating System: basic knowledge of permissions and system structure.
- Bash: basic scripting knowledge.
- Cron: familiarity with the Linux task scheduler.
Step-by-step
1. Make a copy of the current /etc/hosts
content
Copy the current content of the /etc/hosts
file. This will preserve your system's default configuration for later use.
2. Create the script /usr/local/bin/permit_all.sh
This script restores the original /etc/hosts
file, removing any blocking rules. Paste the content you copied in step 1. Example:
#!/bin/bash
sudo tee /etc/hosts > /dev/null <<EOF
127.0.0.1 localhost
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
EOF
Give execution permission to the script:
chmod +x /usr/local/bin/permit_all.sh
3. Create the script /usr/local/bin/block_sites.sh
This script modifies the /etc/hosts
file to block social media by redirecting them to localhost:
#!/bin/bash
sudo tee /etc/hosts > /dev/null <<EOF
127.0.0.1 localhost
127.0.1.1 wolf-notebook
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
#BLACK LIST
127.0.0.1 facebook.com www.facebook.com
127.0.0.1 m.facebook.com static.facebook.com
127.0.0.1 instagram.com www.instagram.com
127.0.0.1 l.instagram.com cdninstagram.com static.cdninstagram.com
EOF
Give execution permission:
chmod +x /usr/local/bin/block_sites.sh
4. Create the script /usr/local/bin/network_control.sh
This script decides which of the previous scripts to run based on the current system time:
#!/bin/bash
HOUR=$(date +%H)
if [ "$HOUR" -ge 8 ] && [ "$HOUR" -lt 20 ]; then
echo "Working hours – blocking sites"
/usr/local/bin/block_sites.sh
else
echo "Off-hours – allowing sites"
/usr/local/bin/permit_all.sh
fi
Give execution permission:
chmod +x /usr/local/bin/network_control.sh
5. Schedule automatic execution with Cron
As root, edit the crontab using:
crontab -e
At the end of the file, add the following lines:
@reboot /usr/local/bin/network_control.sh
@hourly /usr/local/bin/network_control.sh
The @reboot
command ensures the script runs every time the computer starts.
The @hourly
command checks hourly whether it's still working hours.
Final Considerations
You now have a lightweight and effective system to block websites during work hours — ideal for those working from home or looking to reduce distractions without technical complications.