nginx: How To Block Visitors By Country With The GeoIP Module (Debian/Ubuntu)
|
Submitted by falko (Contact Author) (Forums) on Mon, 2012-08-27 17:18. :: Debian | Ubuntu | Web Server | nginx
nginx: How To Block Visitors By Country With The GeoIP Module (Debian/Ubuntu)Version 1.0 This tutorial explains how to use the GeoIP module with nginx to block visitors by country. This is made possible by the GeoIP database which maps users' IP addresses to countries. nginx must be compiled with the HttpGeoipModule to use the GeoIP database. I do not issue any guarantee that this will work for you!
1 Preliminary NoteAs mentioned in the introduction, nginx must be compiled with the HttpGeoipModule. To check if your nginx was compiled with that module, run: nginx -V If you see --with-http_geoip_module in the output, you are ready to use the GeoIP database with nginx: root@server1:~# nginx -V
2 Installing The GeoIP DatabaseOn Debian/Ubuntu, the GeoIP database can be installed as follows: apt-get install geoip-database libgeoip1 This places the GeoIP database in /usr/share/GeoIP/GeoIP.dat. It is possible that it is a bit outdated. Therefore we can optionally download a fresh copy from the GeoIP web site: mv /usr/share/GeoIP/GeoIP.dat /usr/share/GeoIP/GeoIP.dat_bak cd /usr/share/GeoIP/
3 Configuring nginxOpen /etc/nginx/nginx.conf... vi /etc/nginx/nginx.conf ... and place this in the http {} block, before any include lines:
This allows all countries, except the three countries set to no (you can find a list of country codes here). To do it the other way round, i.e. block all countries and allow only a few, you'd do it this way:
Now, this actually doesn't block any country, it just sets the $allowed_country variable. To actually block countries, you must open your vhost configuration and place the following code in the server {} container (this can go inside and also outside any location {} block):
This returns the 444 error code to any visitor from a blocked country. What this does is it closes the connection without sending any headers. You can also use another error code like 403 ("Forbidden") if you like. Reload nginx afterwards: /etc/init.d/nginx reload
4 Links
About The Author![]() Falko Timme is the owner of
|





Recent comments
1 day 7 hours ago
1 day 12 hours ago
1 day 16 hours ago
1 day 18 hours ago
2 days 8 hours ago
2 days 8 hours ago
2 days 13 hours ago
2 days 20 hours ago
2 days 21 hours ago
2 days 22 hours ago