nginx的geoip模块使用

网站须要根据不一样的源地址转发到不一样的二级站点,能够经过ngx_http_geoip_module模块实现。nginx默认不编译这个模块,须要编译时开启--with-http_geoip_module编译选项。ngx_http_geoip_module 模块建立变量,使用预编译的MaxMind数据库解析客户端IP地址,获得变量值,而后根据变量的值去匹配判断,因此要模块依赖MaxMind GeoIP库,GeoIP数据库支持两种格式CSV格式和二进制格式。linux

语法: geoip_country databasenginx

http {
geoip_country GeoIP.dat;
geoip_city GeoLiteCity.dat;
.............................
}数据库

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

 

指定数据库,用于根据客户端IP地址获得其所在国家。 使用这个数据库时,配置中可用下列变量:负载均衡

$geoip_country_codeide

双字符国家代码,好比“RU”,“US”。测试

$geoip_country_code3网站

三字符国家代码,好比“RUS”,“USA”。spa

$geoip_country_namecode

国家名称,好比“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

wKiom1N8IemDqelYAACQJdevd1o957.jpg

修改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地址

wKiom1N8JQWRd_kxAAGBQUi_dLs446.jpg

测试2,使用美国IP地址

wKioL1N8JPmTkmTWAAG-vaVRdDw807.jpg

总结:nginx的geoip模块能够结合upstream来作不一样地域的负载均衡,也能够像个人案例同样根据客户端的IP地址重定向到不一样的分站点。

相关文章
相关标签/搜索