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 TRAFFICgeoip_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 JAPANif ($allow_visit = no) {deny all ;}
** Alternatively, you could redirect the traffic somewhere instead of outright blocking it...
# REDIRECT JAPAN TRAFFICif ($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 TRAFFICgeoip_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 TRAFFICif ($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 TRAFFICif ($allowed_country = yes) { set $exclusions 1; }
if ($exclusions = "0") { return 301 https://www.japanatron.com ; }
Related Articles
Getflix - Netflix Still Not Wo...
There was a recent issue where the Playstation 3 Netflix app stopped working with Getflix--a service I use to watch Netflix here in Japan. Fortunately, Getflix...
How to Spot an iPhone Unlock S...
While Apple technically calls it "iPhone IMEI database whitelisting," it's better known around the web as a factory unlock--a process that allows your iPhone to...
Zimbra - Add Trusted Relay to ...
My domain name registrar offers email aliases and forwarding; however, this feature causes my mail server's SPF checks to fail because the registrar's mail rela...
Nginx - Blocking Access to Joo...
I propose blocking all access to Joomla's administrator login page and front-end user login (if you don't use it) because I constantly see a-hole bots in my log...