14 star shifts of Nginx - (GeoIP)

Posted by Stingus on Tue, 03 Dec 2019 05:17:52 +0100

What is GeoIP

GeoIP refers to the location information such as longitude and latitude, national map, or province (state) by accessing IP. We can use this function to restrict access to a certain country or a certain region, or to realize customized personalized functions.

How to enable GeoIP

# Libmaxminddb (because you need to read the IP database library in GeoIP2, you need to use a C library in libmaxminddb)
wget https://github.com/maxmind/libmaxminddb/releases/download/1.3.2/libmaxminddb-1.3.2.tar.gz
tar zxvf libmaxminddb-1.3.2.tar.gz
cd libmaxminddb-1.3.2
./configure
make
make  install
# Add library path and update library
sh -c "echo /usr/local/lib  >> /etc/ld.so.conf.d/local.conf"
ldconfig
# GeoIP
wget https://github.com/leev/ngx_http_geoip2_module/archive/3.2.tar.gz
tar zxvf 3.2.tar.gz
# Nginx
 ./configure --prefix=/usr/local/nginx --add-module=../ngx_http_geoip2_module-3.2
make & make install
# GeoLite city library and National Library (this library is to translate IP address into specific address information)
wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz
gunzip GeoLite2-City.mmdb.gz
gunzip GeoLite2-Country.mmdb.gz
mkdir /data/geoip
mv GeoLite2-City.mmdb  /data/geoip/city.mmdb
mv GeoLite2-Country.mmdb /data/geoip/country.mmdb
# Modify the configuration file to enable GeoIP
vim /usr/local/nginx/conf/nginx.conf
http {
    geoip2 /data/geoip/country.mmdb {
        $geoip2_data_country_code default=CN country iso_code;
        $geoip2_data_country_name country names en;
    }
    geoip2 /data/geoip/city.mmdb {
        $geoip2_data_city_name default=Shenzhen city names en;
    }

    server {
        listen       80;
        server_name  localhost;
        location / {
            add_header geoip2_data_country_code $geoip2_data_country_code;
            add_header geoip2_data_city_name $geoip2_data_city_name;
            if ($geoip2_data_country_code = CN){
                root /data/webroot/cn;
            }
            if ($geoip2_data_country_code = US){
                root /data/webroot/us;
            }
        }
}

How to check the GeoIP effect

mkdir /data/webroot/us
mkdir /data/webroot/cn
echo "US Site" > /data/webroot/us/index.html
echo "CN Site" > /data/webroot/cn/index.html

According to the visit to ECS in Silicon Valley in the United States, the national information obtained by GeoIP module is US, and the city information is San Mateo.

For the ECS visit in South China, the GeoIP module successfully obtained the national information as CN and the city information as Shenzhen.

Topics: Web Server Nginx Database github vim