Block IP by country

Block IP by country

In some cases, you may want to block all traffic from a specific country to reach your server.

How to:

1- First, make sure that you have iptables and ipset installed

apt update
apt install iptables ipset

2- Then if you want to block Russia for example, create a list containing all IP ranges assigned to Russian country: (you can get IP ranges associated with any country at

ipset create block_russia hash:net
ipset list
wget -O - | sudo awk '{print "add block_russia " $1}' | sudo ipset restore

3- Add a rule into your iptable that block all ranges of that list:

iptables -A INPUT -m set --match-set block_russia src -j DROP

4- Finally make this rule persistent to allow it to survive a reboot of your server

apt install iptables-persistent ipset-persistent
iptables-save > /etc/iptables/rules.v4
ipset save > /etc/iptables/ipset


This is a very effective way to ban traffic and prevent attacks from compromised hosts or script kiddy of a country but will not block more seasoned hackers nor traffic coming from other countries.

Do remember, there is no bulletproof solution when it comes to IT security, so this might enter your security strategy but it shouldn't be your only one line of defense.

A comprehensive security strategy involves multiple layers of defense mechanisms to address the dynamic nature of cyber threats.