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

Where Writing Meets Entrepreneurship!

Get FREE Google Cloud Tutorials.
GET NOW
close-link
Please help us get 1000 likes in Facebook. Thank You!
LIKE NOW

Stay Connected!

Get latest tutorials on Google Cloud and Open Source topics
SUBSCRIBE
close-link