1.重新编译nginx命令,加载ngx_http_geoip2_module模块
1.1安装libmaxminddb依赖
libmaxminddb git地址:GitHub - maxmind/libmaxminddb: C library for the MaxMind DB file format
wget https://github.com/maxmind/libmaxminddb/releases/download/1.6.0/libmaxminddb-1.6.0.tar.gz
tar -xvf libmaxminddb-1.6.0.tar.gz
cd libmaxminddb-1.6.0
./configure --prefix=/usr/
make && make check && make install
#当./configure时,如果没有加--prefix参数将依赖库装到/usr/lib下的话。则可以实用新建软连接的办法
#ln -s /usr/local/lib/libmaxminddb.so.0.0.7 /usr/lib64/libmaxminddb.so.0
ldconfig
1.2重新编译nginx命令文件,加载ngx_http_geoip2_module模块
下载ngx_http_geoip2_module模块
git地址:GitHub - chinagoldline/ngx_http_geoip2_module: Nginx GeoIP2 module
重新编译nginx命令文件
#进入nginx源码文件
cd nginx-1.15.5
#查看此前nginx命令文件编译参数。configure arguments后面就是之前编译参数
nginx -V
#重新编译nginx命令文件,要把之前编译的都带上。然后追加新的模块
./configure --prefix=/home/service/app/nginx/ --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --with-http_realip_module --with-http_v2_module --with-pcre --add-module=/home/service/app/nginx-1.15.5/ngx_http_geoip2_module/
#编译,迁完不要make install!!!
make
替换nginx命令,新编译的nginx命令在源码纹加下的objs目录下
#备份旧文件
mv nginx/sbin/nginx nginx/sbin/nginx-bak
#替换
cp ./nginx-1.15.5/objs/nginx nginx/sbin/
#验证编译模块
./nginx/sbin/nginx -V
2.下载安装GeoIP数据库
需要先注册账号,登陆后即可下载文件。注册账号的时候不要连接VPN或者代理,不然会一直报错。
GeoIP2-Country:GeoIP2 Country Database | MaxMind
GeoIP2-City:GeoIP2 City Database | MaxMind
或者我的CSDN也上传了文件:
GeoLite2-Country_20220118-Web服务器文档类资源-CSDN下载
GeoLite2-City_20220118-Web服务器文档类资源-CSDN下载
3.配置nginx
http {
......
geoip2 /home/service/app/nginx/conf/GeoLite2-Country.mmdb {
auto_reload 5m;
$geoip2_metadata_country_build metadata build_epoch;
$geoip_country_code default=US country iso_code;
$geoip_country_name country names en;
}
geoip2 /home/service/app/nginx/conf/GeoLite2-City.mmdb {
$geoip2_data_city_name city names en;
}
server {
......
location / {
default_type application/json;
return 200 '{"ip":$remote_addr,"countryCode":"$geoip_country_code"};';
}
......
}