Tengine geoip模块动态加载和配置

老功能了,不多说,直接来步骤:

下载需要的文件:

wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP.tar.gz

 

tar -zxvf GeoIP.tar.gz

cd GeoIP-1.4.8/

./configure

Make

Make install

echo ‘/usr/local/lib’ > /etc/ld.so.conf.d/geoip.conf

ldconfig

wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz

wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz

gzip -d GeoIP.dat.gz

gzip -d GeoLiteCity.dat.gz

mv GeoIP.dat GeoLiteCity.dat /usr/local/nginx/conf/

如果改完配置后哟与如下报错就需要加载geo模块,下面有介绍:

nginx: [emerg] unknown directive “geoip_country” in /etc/nginx/nginx.conf:67

 

动态安装geo模块, 整个过程不影响现在的Nginx访问,安装完reload nginx就可以生效了:

进入Nginx安装包目录,我的在/usr/local/src/tengine-2.1.2/下

./configure –with-http_geoip_module=shared

Make

make dso_install

然后在nginx.conf里加入:

dso {

load ngx_http_geoip_module.so;

}

#geo

geoip_country  /usr/local/nginx/conf/GeoIP.dat;

geoip_city  /usr/local/nginx/conf/GeoLiteCity.dat;

 

加入日志中:

log_format  main  ‘$remote_addr – $remote_user [$time_local] “$request” ‘

‘$status $body_bytes_sent “$http_referer” ‘

‘”$http_user_agent” “$http_x_forwarded_for” ‘

‘”$upstream_addr” “$upstream_cache_status” ‘

‘”$upstream_status” “$upstream_response_time” “$cookie_jsessionid” “$request_time” “$

host” “–$geoip_country_name–$geoip_city–$geoip_postal_code”‘;

查看访问日志确认可以。

其它有用配置:

禁止国家访问:

if ($geoip_country_code = CN) {
  deny all;
}
GeoIP 中跟国家相关的变量:

GeoIP 中跟国家下级区域相关的变量:

网上有用来做负载均衡的例子:

另一个用法:

在 php 中测试 GeoIP

首先需要在 fastcgi_params 或 fastcgi.conf 中引入 GeoIP 的属性,

如需Nginx传递变量给PHP,编辑fastcgi_params添加:

php代码:

或者:

官方介绍:http://nginx.org/en/docs/http/ngx_http_geoip_module.html

 

发表评论