【笔记】Nginx在响应头中添加访问者的地理位置

前言

Nginx在响应头中添加访问者的地理位置

安装依赖库

1
2
3
4
5
6
7
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
echo /usr/local/lib >> /etc/ld.so.conf.d/local.conf
ldconfig
cd ..

下载Geoip2数据库

  • MaxMind官网下载GeoLite2数据库,存放在/usr/share/GeoIP/目录下
    • 国家数据库:GeoLite2-Country.mmdb
    • 城市数据库:GeoLite2-City.mmdb

手动搜索IP地址的国家

<ip>:需要搜索的IP地址

1
mmdblookup -f /usr/share/GeoIP/GeoLite2-City.mmdb -i <ip>

重新编译包含GeoIP2模块的Nginx

下载Nginx的GeoIP2模块源码

1
git clone https://github.com/leev/ngx_http_geoip2_module

重新编译Nginx

<ngx_http_geoip2_module>:GeoIP2源码存放路径

1
2
3
4
5
6
7
wget http://nginx.org/download/nginx-1.18.0.tar.gz
tar -xvf nginx-1.18.0.tar.gz
cd nginx-1.18.0
./configure --add-module=<ngx_http_geoip2_module>
make && make install
/usr/local/nginx/sbin/nginx -V
cd ..

配置Nginx

/usr/local/nginx/conf/nginx.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
http {

geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
$geoip2_country_code country iso_code;
}

server {
listen 80;

location / {
add_header Country $geoip2_country_code;
root /usr/share/nginx;
index index.html;
}
}

}

完成

参考文献

知乎——ar414
博客园——tongyongliang
阿舟哦的博客