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地址重定向到不一樣的分站點。

相關文章
相關標籤/搜索