Country Blocking with nginx GeoIP on Ubuntu/Debian

On Ubuntu/Debian, install nginx geoip module with

apt install geoip-database libgeoip1 libnginx-mod-http-geoip -y

Now edit nginx.conf

vi /etc/nginx/nginx.conf

Find

http {

Add below

geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $my_country_blocker {
    default no;
    US yes;
    AU yes;
    CA yes;
}

nginx geoip

You can add 2 letter country code and set ye/no as required.

To implement GeoIP blocking for a web site, you need to edit server entry for the web site. In this cause, i will use the default web site.

vi /etc/nginx/sites-enabled/default

Find

server {

Add blow

if ($my_country_blocker = no) {
    return 444;
}

nginx geoip server configuration

This will block access to the web site from any country that is not listed in nginx.conf

You need to restart nginx web server

systemctl restart nginx

If you need to redirect blocked users to another site, use

if ($my_country_blocker = no) {
    rewrite ^ https://google.com break;
}

This will redirect the visitor to google if their country is not US, AU or CA.

See Nginx

Need help with Linux Server or WordPress? We can help!

Leave a Reply

Your email address will not be published. Required fields are marked *