First I need to make sure my Nginx has the geoip module.
Check it by entering the command below.
nginx -V |
My Nginx shown the results as below.
nginx version: nginx /1 .14.1 built with OpenSSL 1.1.1 11 Sep 2018 TLS SNI support enabled configure arguments: --with-cc-opt= '-g -O2 -fdebug-prefix-map=/build/nginx-urYIzg/nginx-1.14.1=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Wdate-time -D_FORTIFY_SOURCE=2' --with-ld-opt= '-Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -fPIC' --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/nginx .pid --modules-path= /usr/lib/nginx/modules --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-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_v2_module --with-http_dav_module --with-http_slice_module --with-threads --with-http_addition_module --with-http_geoip_module=dynamic --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module=dynamic --with-http_sub_module --with-http_xslt_module=dynamic --with-stream=dynamic --with-stream_ssl_module --with-stream_ssl_preread_module --with-mail=dynamic --with-mail_ssl_module --add-dynamic-module= /build/nginx-urYIzg/nginx-1 .14.1 /debian/modules/http-auth-pam --add-dynamic-module= /build/nginx-urYIzg/nginx-1 .14.1 /debian/modules/http-dav-ext --add-dynamic-module= /build/nginx-urYIzg/nginx-1 .14.1 /debian/modules/http-echo --add-dynamic-module= /build/nginx-urYIzg/nginx-1 .14.1 /debian/modules/http-upstream-fair --add-dynamic-module= /build/nginx-urYIzg/nginx-1 .14.1 /debian/modules/http-subs-filter |
I found –with-http_geoip_module=dynamic
It is cool, I have the geoip module with my Nginx installation.
Second, I need GeoIP country database.
Here is the official site to download the database.
I use the commands in my terminal window.
wget http: //geolite .maxmind.com /download/geoip/database/GeoLiteCountry/GeoIP .dat.gz gunzip GeoIP.dat.gz sudo mkdir /etc/nginx/geoip sudo copy GeoIP.dat /etc/nginx/geoip |
Last, Modify Nginx config files
Edit the /etc/nginx/nginx.conf
In the http block, add following code.
geoip_country /etc/nginx/geoip/GeoIP .dat |
Edit my website config file, /etc/nginx/conf.d/mysite.conf
Find the location block, I add the following code.
if ($geoip_country_code = "CA" ){ return 403; } |
Here, Country Code, or “CA”, is an example. You can use any two-letter country code, such as RU, US, CN.
It is also very useful, when I want to setup some sub-website for the users from different country.