Blocking country with Nginx without GeoIP module

There are always many solution to solve a single problem, if you prefer to use the Nginx GeoIP module, you may refer back to the previous post on the detail and step. In this article, I will share on how to do the blocking of country without the plugin module.

Compare to the previous method, by using the country CIDR list may have some draw back
1. The country list may not up to date as compare to the list download from GeoIP website
2. It may inccur more overhead depand on the country list your server may need to check through

But compare to the previous method, this will be more simple and straigh forward. Thanks to https://www.gypthecat.com who created a little site to share out the country cidr list which we may just directly download from

 

Step 1: Install the unzip

$ sudo apt-get install unzip 

Step 2: Create a folder

$ sudo mkdir /etc/nginx/country-cidr && cd /etc/nginx/country-cidr

Step 3: Download database

$ sudo wget http://firewalliplists.gypthecat.com/lists/nginx/nginx-countries.conf.zip

Step 4: Unzip the file

$ sudo unzip nginx-countries.conf.zip

You should now have a directory full of some configuration files for nginx, labelled as both allow and deny.

Step 5: Start configure the vhost in Nginx

server
{
listen 80;
server_name www.companya.com companya.com;
root /webhost/companya.com/httpdocs/;
access_log /webhost/companya.com/logs/access.log combined;
error_log /webhost/tld.co.uk/logs/error.log;
index index.php index.html index.htm;

location /
    {
    allow 175.143.25.75;
    include country-cidr/MY-deny.conf;
    allow all;
    # Do something here
    }

}

The above example show that we allow the IP of 175.143.25.75 but block the access from all Malaysia IP, allow other country IP to be access. You may add in more country list to block or allow, if you want to allow only certain IP out of the block country list, you may place the allow list above your deny include file, which will overwrite the deny list.

 

Step 6: Restart Nginx

$ sudo service nginx reload

That’s it, the configure should work and you may play around with the list that you wish to deny and allow.

More reading on https://www.gypthecat.com/blocking-countries-on-nginx-without-the-geoip-module

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: