Japanatron Logo

I've been figuring out how to block or redirect web traffic in Nginx based on the country geoIP.

NOTES
* You need the package nginx-extras for this because this package has the geoIP Nginx plugin.
* I used Japan (JP) in these examples, so change the country code to whatever you wish.

APPROACH #1 - BASIC
This uses a locally-downloaded GeoIP database.

I. This goes in the HTTP block. It basically flags traffic from countries you specify.

# DETECT JAPAN TRAFFIC
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allow_visit {
default yes;
JP no;
}

II. This goes in the SERVER block. It sets the action you want on the country IP flag you set.

# BLOCK ACCESS FROM JAPAN
if ($allow_visit = no) {
deny all ;
}

** Alternatively, you could redirect the traffic somewhere instead of outright blocking it...

# REDIRECT JAPAN TRAFFIC
if ($allow_visit = no) {
return 301 https://www.japanatron.com/ ;
}

APPROACH #2 - ADVANCED
This approach allows you to set exceptions, like for whitelisted IP addresses.

I. This goes in the HTTP block:

# DETECT JAPAN TRAFFIC
geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allowed_country {
default yes;
JP no;
}

geo $exclusions {
default 0;
111.222.333.444/32 1;
}

II. This goes in the SERVER block:

# REDIRECT JAPAN TRAFFIC
if ($allowed_country = yes) {
set $exclusions 1;
}

if ($exclusions = "0") {
return 301 https://www.japanatron.com ;
}

APPROACH #3 - CLOUDFLARE IP COUNTRY HEADER
If you use Cloudflare's reverse proxy / CDN service, you can read the geoIP information from Cloudflare's headers. This is my favorite approach because it doesn't require locally downloading and maintaining a geoIP database.

I. This goes in the HTTP block:

# DETECT JAPAN TRAFFIC (CLOUDFLARE HEADER)
map $http_cf_ipcountry $allowed_country {
default yes;
JP no;
}

geo $exclusions {
default 0;
111.222.333.444/32 1;
}

II. This goes in the SERVER block:

# REDIRECT JAPAN TRAFFIC
if ($allowed_country = yes) {
set $exclusions 1;
}

if ($exclusions = "0") {
return 301 https://www.japanatron.com ;
}

Related Articles

Windows - How to Run Add Print...

I had an end user that wanted to install their home printer drivers on their office laptop.  I took remote control of their PC, but to my chagrin the user lacke...

The Hunt for the Ultimate Blue...

I'm obsessed with bluetooth.  So much so that I've been hunting for heaven's own pair of bluetooth headphones for my Tokyo subway commutes.  I'm already on my 5...

Combine Image File and Audio F...

I wanted to figure out a way to quickly and easily combine an image file (jpg) and audio file (mp3) into a video file (mov) using the free media converter tool ...

The Hunt for the Ultimate VPS ...

If IT geek-dom were a crime, I'd be on death row by now.  Fortunately, it is not; so I continue my dorky IT pursuits--the latest of which is finding a VPS cloud...