We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

How to Block a Website visitors from certain countries using Nginx GeoIP

Prerequisites

  1. Your Compute Engine Instance running.
  2. For setting up Compute Engine, see the Setting up Compute Engine Instance.
  3. For installing Nginx and PHP, see how to install LEMP in Compute Engine Instance.
  4. Domain name is pointed to your virtual machine. Learn how to Set up Google Cloud DNS for your domain.

Block using GeoIP

With Nginx, blocking people from certain countries can be accomplished using the GeoIP module.

First, you’ll need to make sure that you have the GeoIP database installed.

SSH to your server and install GeoIP

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

Once this is installed or pre-installed in your server you can proceed to the configuration.

Edit your Nginx configuration for your website.

sudo nano /etc/nginx/sites-available/yourdomainname.com

Add the following code above the server block to block visitors from US country.

geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allow_visit {
default yes;
US no;
#You can add additional countries
}

You can also allow visitor from certain countries and block every other.

geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allow_visit {
default no;
US yes;
#You can add additional countries
}

Now add the following inside your server block before location block.

if ($allow_visit = no) {
#You can also use custom page redirection or whatever you need
return 403;
}

With the above code if a visitor visits your website from US they will get 403 Forbidden error.

This setup is tested with Nginx version 1.14.*

I hope this post helps you to block your website visitors from certain countries using GeoIP.

12
737.228,30