GeoIP country blocking - whitelist specific IPs

Hello NGINX users,

I’m facing a little issue with country bans over GeoIP. I’m using the
following code within my server directive:

if ($geoip_country_code ~ (BR|CN|KR|RU) ) {
return 123;

123 returns an error page informing the visitor that his country is
Now let’s say I’ve got some visitors from russia, who should still be
to access my website. How would I archive this? Of course something like
“allow;” doesn’t work with the code above. Any suggestions?

Thanks in advance!

Posted at Nginx Forum:


We use something similar to this:

geoip_country /path/to/GeoIP.dat;

geo $allowed_ranges {
default 0; 1; 1; 1;

map $geoip_country_code $blocked_country {
default 1;
A2 0; # Satellite Provider
O1 0; # Other Country
AD 1; # Andorra
AP 1; # Asia/Pacific Region
AQ 1; # Antarctica

if ($blocked_country) {
set $deny_request 1;

if ($allowed_ranges) {
set $deny_request 0;

if ($deny_request) {

Do whatever you want to do here …


Hope that it makes sense? :slight_smile:



thanks for your reply! Your solution does indeed make sense and I’ve
using something similar before. Just thought there might be something
wouldn’t require rewriting my current syntax, such as:

if ($geoip_country_code ~ (BR|CN|KR|RU) ) {
if ($remote_addr = (|| ) {
return 123;

Posted at Nginx Forum:

…or some elif function, but you get the idea.

Posted at Nginx Forum: