NGINX geoip module

I am using ubuntu 16 and tryign to get the geoip filter to work. I have loaded the nginx.conf file with the geoip_country and city database files withint the http block, but i am not sure what to do with the sites-available/default server block to access the country code from the geoip module as it seems to not be working.


Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hello, @nove1398

This is a good question. I’ll try to answer it by giving an example on how to block a country

To tell nginx where the GeoIP databases are located you need to add these lines into /etc/nginx/nginx.conf in your http { block

geoip_country /usr/share/GeoIP/GeoIP.dat;
geoip_city /usr/share/GeoIP/GeoIPCity.dat;

I put it at the top here nginx configuration
user www-data;
worker_processes auto;
pid /run/;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        multi_accept on;

http {
    # GeoIP databases
    geoip_country /usr/share/GeoIP/GeoIP.dat;
    geoip_city /usr/share/GeoIP/GeoIPCity.dat;

The full list of MaxMind GeoIP country codes in 2 letter format can be found here

# map the list of denied countries
map $geoip_country_code $allowed_country {
   default yes;
   # Pakistan
   PK no;
   # Ukraine
   UA no;
   # Russia
   RU no;
   # China
   CN no;

Now we can block the country with this if statement

# block the country
if ($allowed_country = no) {
    return 444;

If you want to add a custom HTTP header to show the country you can do so with this snippet in the nginx server block.

add_header X-Country $geoip_country_code;

As usual after you finish making any of these modifications you should test your nginx configuration

nginx -t

If the syntax is OK then reload nginx

service nginx reload

Hope this helps!

Regards, Alex