Block entire countries from accessing site using ufw on Linux

Recently one of my sites started to get very slow and unresponsive.

Posted by Luke on Sat, 09 Nov 2019 9:24:00

Recently one of my sites started to get very slow and unresponsive. After analyzing Apache access log I have figured out that there is a lot of strange requests coming from China.

I have enabled GEO blocking on an Apache level but day after traffic from China increased to the levels that the site started to slow down again. Apache had to display “You are not authorized” page to each request coming from China anyway so it was exhausting its resources.

And so I had to block this traffic on an OS level by firewall. There is a very handy site coming to your rescue –>http://www.ip2location.com/free/visitor-blocker where you can download a CIDR formatted text file with IP addresses from a chosen country. Get the file and save it. Rename it (in my case filename was china.txt).

After you downloaded the file everything is relatively easy:

sudo while read line; do sudo ufw insert 1 deny from $line to any; done < china.txt

For big country it might take even hours to complete. After it’s done check ufw:

sudo ufw status

It should look similar to the screenshot below:

In case you want to remove the rules run following command:

sudo while read line; do sudo ufw delete deny from $line; done < china.txt