Compute Engine Google Cloud

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.
PlatformRAMSSDCost
Alibaba Cloud512 MB20 GB$2.50/mo
Cloudways – Managed Cloud1 GB25 GB$10/mo
Kinsta – Google Cloud Managed WP1 Website10 GB$30/mo

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 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.

Write A Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.