您的位置:首页 > 运维架构 > Nginx

nginx的geoip模块使用

2014-05-21 11:17 302 查看
网站需要根据不同的源地址转发到不同的二级站点,可以通过ngx_http_geoip_module模块实现。nginx默认不编译这个模块,需要编译时开启
--with-http_geoip_module
编译选项。ngx_http_geoip_module 模块创建变量,使用预编译的MaxMind数据库解析客户端IP地址,得到变量值,然后根据变量的值去匹配判断,所以要模块依赖MaxMind GeoIP库,GeoIP数据库支持两种格式CSV格式和二进制格式。
语法: geoip_country database
http {
geoip_country GeoIP.dat;
geoip_city GeoLiteCity.dat;
.............................
}

location / {
if ($geoip_city_country_code ~ "US") {
proxy_pass http://USA$request_uri; }
}

指定数据库,用于根据客户端IP地址得到其所在国家。 使用这个数据库时,配置中可用下列变量:
$geoip_country_code
双字符国家代码,比如“RU”,“US”。
$geoip_country_code3
三字符国家代码,比如“RUS”,“USA”。
$geoip_country_name
国家名称,比如“Russian Federation”,“United States”。
这个二进制数据库文件可以从maxmind官网下载
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gzip -d GeoIP.dat.gz
mv GeoIP.dat /usr/local/nginx/conf/GeoIP.dat

但是这种使用二进制数据库文件存在一个问题:数据库不是很准确但由于是数据文件不能直接修改,所以我们使用自己收集整理的数据库文件或者下载maxmind提供的cvs格式明文数据库文件修改后再使用。
wget http://geolite.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip
unzip GeoIPCountryCSV.zip
mv GeoIPCountryWhois.csv /usr/local/nginx/conf/GeoIPCountryWhois.csv

然后使用一个perl脚本去整理这个文件并保存为txt文件
geo2nginx.pl < GeoIPCountryWhois.csv > nginx_geoip.txt



修改nginx.conf
在http标签里增加如下
geo $geoip_country {
include nginx_geoip.txt;
}
在location标签里修改如下
server {
listen 80;
server_name linuxom.com;
if ( $geoip_country ~ ^(?:CN)$ ){
rewrite ^(.*) http://www.baidu.com$1 break; //如果访问的客户端ip的code为CN中国,那么转向到baidu
}
if ( $geoip_country ~ ^(?:US)$ ){
rewrite ^(.*) http://www.sina.com.cn$1 break; //如果访问的客户端ip的code为US美国,那么转向到sina

}

平滑重启nginx
/usr/local/nginx/sbin/nginx -s reload
测试1,使用中国IP地址



测试2,使用美国IP地址



总结:nginx的geoip模块可以结合upstream来做不同地域的负载均衡,也可以像我的案例一样根据客户端的IP地址重定向到不同的分站点。
本文出自 “老徐的私房菜” 博客,谢绝转载!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: