you need to restrict access to the site from certain countries using the nginx and GeoIP module

The fact is that we are working with the platform and nginx is already configured out of the box there, but you can block only the built-in platform tools and only certain parts of the site. I would like to do something centrally.

use ubuntu 12.04, can there be any other ways of software blocking access?

  • Googling for "nginx geoip reject country". There are enough answers. - Vitaly Karpenko

1 answer 1

Have you already set the geoip_country variable? It is specified in the http block and indicates the path to the file - the GeoIP database. If it is already configured, you can use the $geoip_country_code and $geoip_country_code that return two and three letter country codes. Further, it will be convenient to use the map directive, in the same http block, in about the same way:

 map $geoip_country_code $you_shall_not_pass { default yes; RU no; BY no; KZ no; } 

In this variant, if the $geoip_country_code variable has the values RU , BY , KZ , then the $you_shall_not_pass variable will take the value no . In all other cases, yes .

Now, in the server block of the desired site, you can write the following restriction in a specific location :

 if ($you_shall_not_pass = yes) { return 444; } 

That is, if the $you_shall_not_pass variable is set to yes , that is, the code is strange does not belong to the allowed ones and the request should not pass, then ... it does not pass. How to change the configuration for the option if you need permission by default, and a ban for the listed countries, I think it is not necessary to explain.

  • if I understand correctly, then in the config I need to create a location / and add an if condition? - Danylo
  • @DanilGetmantsev depends on what part of the site you want to close. All, or, for example, only admin panel ... If all, then yes - it should be in location / . - MAN69
  • strangely, when trying to initialize a variable in nginx.conf, it beats an error and refers to unknown directive $ geoip_country, I understand that this indicates that the module is not connected. nginx -V indicates that the module --with-http_geoip_module = dynamic is installed. I can not understand what could be plugging. Can the access rights (www-data, 755) to the GeoIP.dat file somehow influence the variable initialization process? - Danylo
  • the file is simply not readable and the comparison across the country does not happen .. - Danylo
  • one
    @ DanielGetman: load the dynamic module with this command: load_module "modules/ngx_http_geoip_module.so"; . This is done in the main block. serverfault.com/questions/797850/… - MANKK