Get Started With IP2location Nginx Module
Dependencies
This module requires IP2Location BIN database to function. You may download the BIN database at
IP2Location LITE BIN Data (Free): https://lite.ip2location.com
IP2Location Commercial BIN Data (Comprehensive): https://www.ip2location.com
Installation
Download IP2location C library from here.
Compile and install IP2Location C library.
-
Download IP2Location module and decompress the package.
wget https://github.com/ip2location/ip2location-nginx/archive/master.zip unzip master.zip rm master.zip
-
Download the latest Nginx source code from here.
wget https://nginx.org/download/nginx-x.y.z.tar.gz
-
Decompress and go into Nginx source directory.
tar xvfz nginx-x.y.z.tar.gz cd nginx-x.y.z
-
Re-compile Nginx from source to include this module.
Static Module
./configure --add-module=/absolute/path/to/nginx-ip2location-master make make install
Dynamic Module
./configure --add-dynamic-module=/absolute/path/to/nginx-ip2location-master make make install
-
Edit your Nginx config file (nginx.conf), add the following lines under `http` context:
http { ... ip2location_database /usr/share/ip2location/DB6.BIN; ip2location_proxy_recursive on; ip2location_proxy 192.168.1.0/24; }
Sample Codes
Block single country
if ( $ip2location_country_short = 'US' ) {
return 444;
}
Block mutiple countries
map $ip2location_country_short $blacklist_country {
default no;
AU yes;
IN yes;
NG yes;
}
server {
...
if ( $blacklist_country = yes ) {
return 444;
}
}
Redirect visitors from Canada, United States, and Mexico to new page
if ( $ip2location_country_short ~* "CA|US|MX" ) {
rewrite ^ http://example.com/newpage.html permanent;
}