How to block a Country using Nginx

This time I wanted to block an entire country from one single website, and the best way to do it was using allow/deny options inside the virtual host configuration. Blocking a country using Nginx is pretty easy, see the example below:

Go to http://www.incredibill.me/htaccess-block-country-ips, select your country , click on Generate .htaccess code, and you will get many lines like these:

# BLOCK COUNTRY BY IP RANGE
# IncrediBILL’s HTACCESS Tools
# http://incredibill.me

order allow,deny
#
# Block from ALBANIA (AL)
#
deny from 31.22.48.0/20
deny from 31.44.64.0/20
deny from 31.171.152.0/21
deny from 31.222.40.0/21

The ones that we only need to care about are the ones starting with “deny from…”

Pick up all those deny lines, delete all the “from” words you get, and add “;” to the end of each line, so, all lines should be like this:

deny 31.22.48.0/20;
deny 31.44.64.0/20;
deny 31.171.152.0/21;
deny 31.222.40.0/21;

At the end of all the deny lines, add this:

allow all;

So, it should look like this:

deny 31.22.48.0/20;
deny 31.44.64.0/20;
deny 31.171.152.0/21;
deny 31.222.40.0/21;
allow all;

Now let’s add those nasty IPs to Nginx:

nano -w /etc/nginx/block-country.conf

Now edit your virtual host configuration, and include that block configuration into a location block, example:

location / {
root /var/www/yoursite.com;
index index.php;

include /etc/nginx/block-country.conf;
}

As you see, we used the include function to insert the allow/deny configuration into our virtual host config.

Alright, now reload Nginx to apply the changes:

service nginx reload

Testing Nginx Country Block

Use a proxy from your blocked country and if your block configuration is working fine, you shouldn’t be able to see your website.

上一篇: