1,配置http_geoip_module模块。
我们可以配置nginx的模块http_geoip_module进行客户端IP判断国家代码或者城市属性(这里只介绍些国家代码判断),这个http_geoip_module模块需要geo数据库和读取数据库的库文件,nginx编译的时候需要将这个模块编译进去才行。
如果是已经安装过nginx的,可以参考 《原已经安装好的nginx如何查看已经安装模块和添加一个未被编译安装的模块》单独添加。
wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP-1.4.8.tar.gz ./configure make make install
这时可以看到/usr/local/share/GeoIP/GeoIP.dat 生成。
配置好以后,nginx编译参数注意设置:
./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_geoip_module
nginx安装完以后,查看nginx编译参数:
[root@21yunwei~]# /usr/local/nginx/sbin/nginx -V nginx version: nginx/1.10.3 built by gcc 4.4.7 20120313 (Red Hat 4.4.7-17) (GCC) built with OpenSSL 1.0.1e-fips 11 Feb 2013 TLS SNI support enabled configure arguments: --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_geoip_module
2,修改nginx配置文件nginx.conf
配置参数如下:
log_format main '$remote_addr[$geoip_country_code] - $remote_user [$upstream_addr] [$upstream_response_time] [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" "$http_accept_language"'; access_log /logs/nginx/access.log main; geoip_country /usr/local/share/GeoIP/GeoIP.dat;
重启nginx:
/usr/local/nginx/sbin/nginx -s reload
查看最后一行访问日志:
[root@21yunwei ~]# tail -1 /logs/nginx/access.log 121.88.22.15[CN] - - [-] [-] [17/Feb/2017:13:18:52 +0800] "GET /favicon.ico HTTP/1.1" 304 0 "http://test.21yunwei.com/1.php" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36" "-" "zh-CN,zh;q=0.8"
国家代码判断成功。
3,强判断代码加入到php变量中。
修改nginx配置目录下的fastcgi_params 文件,设置添加参数:
fastcgi_param COUNTRY_CODE "$geoip_country_code"; fastcgi_param HTTP_COUNTRY_CODE "$geoip_country_code";
重启nginx加载服务后查看php 变量:
设置完成。
配置实现的参考文档:
Nginx服务器中配置GeoIP模块来拦截指定国家IP http://www.jb51.net/article/86850.htm
转载请注明:21运维 » Nginx配置GeoIP模块并添加国家代码到php变量中