Nginx 利用 IP2Locaion 实现地区负载均衡和 IP 定位

Nginx 利用 IP2Locaion 模块实现地区负载均衡和IP定位。

由于GeoIP2的效率实在是“惊人”,和那“高到爆”的识别精度,真是让人想爆粗口。经过权衡,将IP定位模块更换为 IP2Locaion。

如果还没安装 IP2Location C Library,请先移步到 https://www.24kplus.com/linux/871.html 安装 IP2Location C Library

下载 Nginx IP2Locaion 模块

git clone https://github.com/ip2location/ip2location-nginx.git

查看当前 Nginx 版本信息

nginx -V

可以看到 Nginx 的版本为1.16.0 和 configure 参数,把 configure 参数拷贝保存下来,后面需要用到

到官网 https://nginx.org/en/download.html 找到对应的版本源码下载并解压。本站以1.16.0为例:

下载并解压

wget https://nginx.org/download/nginx-1.16.0.tar.gz
tar -zxf nginx-1.16.0.tar.gz
cd nginx-1.16.0

备用下载地址: https://down.24kplus.com/linux/nginx-1.16.0.tar.gz

生成新的 nginx

把刚刚复制的 configure 参数粘贴到 ./configure 后面, 在结尾处加入 -–add-module=../ip2location-nginx

./configure \
--prefix=/etc/nginx \
.....
# 在结尾处加入一行
-–add-module=../ip2location-nginx
# 如果想编译为动态模块,则添加
--add-dynamic-module=../ip2location-nginx
make

编译好之后不要安装, 停止 nginx 服务

systemctl stop nginx

复制编译好的新 nginx 文件拷贝到sbin下

cp /usr/sbin/nginx /usr/sbin/nginx.bak
cp objs/nginx /usr/sbin

编辑 nginx.conf 文件,在 http {} 中加入以下代码:

http {
……
#doc https://github.com/ip2location/ip2location-nginx
# on 为启用,off 为禁用
ip2location on;
#/usr/share/IP2Location/IP2LOCATION-LITE-DB3.BIN 替换成你的 IP2Locaion 数据路径。
ip2location_database /usr/share/IP2Location/IP2LOCATION-LITE-DB3.BIN;
# 可选参数 ip2location_access_type file_io|shared_memory|cache_memory
# 默认为 shared_memory
# 建议不要选择 file_io, 否则可能会严重拖慢响应速度。
ip2location_access_type shared_memory
……
}

官方提供免费版BIN文件下载: https://lite.ip2location.com/ip2location-lite ,根据自己的需要下载对应版本。

编辑 fastcgi_params 文件,在结尾加入以下几行代码(可选):

#IP2Location, with ip2location on;
fastcgi_param  IP_COUNTRY_CODE		$ip2location_country_short;
fastcgi_param  IP_COUNTRY_NAME		$ip2location_country_long;
fastcgi_param  IP_REGION_NAME		$ip2location_region;
fastcgi_param  IP_CITY_NAME  		$ip2location_city;

更多参数查考官方文档:https://github.com/ip2location/ip2location-nginx

启动 nginx 服务

systemctl start nginx

在 phpinfo 信息中可以看到:

当然,也可以在 nginx 中直接使用 $ip2location_country_short,$ip2location_region等变量来实现地区负载均衡。