Geoip and Nginx How to block visitors by country


Operating system: Ubuntu 16.04

First we need to know nginx has support Geoip:

$ nginx -V
nginx version: nginx/1.10.3 (Ubuntu)
built with OpenSSL 1.0.2g 1 Mar 2016
TLS SNI support enabled
configure arguments: --with-cc-opt='-g -O2 -fPIE -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2'
--with-ld-opt='-Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now' --prefix=/usr/share/nginx --conf-path=/etc/nginx/nginx.conf
--http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/run/
--http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-proxy-temp-path=/var/lib/nginx/proxy
--http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-debug --with-pcre-jit --with-ipv6 --with-http_ssl_module
--with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_addition_module --with-http_dav_module
--with-http_geoip_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_v2_module
--with-http_sub_module --with-http_xslt_module --with-stream --with-stream_ssl_module --with-mail --with-mail_ssl_module --with-threads

yes, we have.

Install geoip packages:

$ sudo apt-get install geoip-database

place for database is:


GeoIP.dat    - > for IPv4

GeoIPv6.dat - > for IPv4 and IPv6

Go to nginx config:

$ cd /etc/nginx

in section http add follow rows:

geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allow_visit {
default no;
US yes;    # enable USA IPs
CA yes;    # enable Canada IPs
} geo $exclusions {
default 0; 1; # here comes allowed IP that is in blocked country list 1; 1; 1; } # Rest of config


save it and go to virtual server (dir sites-enabled)

add follow in section server

server {
#.... some config
location / {
if ($allow_visit = yes) {
set $exclusions 1;
if ($exclusions = "0") {
return 403;
} #... # rest of config  }

almost done

restart nginx

sudo /etc/init.d/nginx reload
[ ok ] Reloading nginx configuration (via systemctl): nginx.service.

You can check availability your site from any place with online services.

Currently unrated


There are currently no comments

New Comment


required (not published)