Get Started With IP2location Nginx Module

Dependencies

This module requires IP2Location BIN database to function. You may download the BIN database at


Installation

  1. Download IP2location C library from here.

  2. Compile and install IP2Location C library.

  3. Download IP2Location module and decompress the package.

    wget https://github.com/ip2location/ip2location-nginx/archive/master.zip
    unzip master.zip
    rm master.zip
    
  4. Download the latest Nginx source code from here.

    wget https://nginx.org/download/nginx-x.y.z.tar.gz
    
  5. Decompress and go into Nginx source directory.

    tar xvfz nginx-x.y.z.tar.gz
    cd nginx-x.y.z
    
  6. 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
    
  7. 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;
}

IP2Location Sample Database (BIN)

The sample BIN files have a limited scope and are only valid for the following IP ranges:

  1. IPv4 : 0.0.0.0 - 7.255.255.255
  2. IPv6 : 2a04:0000:0000:0000:0000:0000:0000:0000 - 2a04:ffff:ffff:ffff:ffff:ffff:ffff:fff

Articles & Tutorials