使用 Nginx 和 GeoIP 模塊來處理不一樣國家的訪問

轉載自:nginx

http://onlyzq.blog.51cto.com/1228/533162
數據庫


安裝 Nginx
由於要用到 http_geoip_module 模塊,系統自帶的 nginx 通常不帶這個模塊,因此要下載 nginx 源代碼後自行編譯:api

# wget http://nginx.org/download/nginx-0.9.6.tar.gz
# tar zxvf nginx-0.9.6.tar.gz
# cd nginx-0.9.6
# ./configure --without-http_empty_gif_module --with-poll_module \
--with-http_stub_status_module --with-http_ssl_module \
--with-http_geoip_module
# make; make install服務器


安裝 MaxMind 的 GeoIP 庫
MaxMind 提供了免費的 IP 地域數據庫(GeoIP.dat),不過這個數據庫文件是二進制的,須要用 GeoIP 庫來讀取,因此除了要下載 GeoIP.dat 文件外(見下一步),還須要安裝能讀取這個文件的庫。編輯器

# wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP.tar.gz
# tar -zxvf GeoIP.tar.gz
# cd GeoIP-1.4.6
# ./configure
# make; make install
剛纔安裝的庫自動安裝到 /usr/local/lib 下,因此這個目錄須要加到動態連接配置裏面以便運行相關程序的時候能自動綁定到這個 GeoIP 庫:ide

# echo '/usr/local/lib' > /etc/ld.so.conf.d/geoip.conf
# ldconfig網站


下載 IP 數據庫
MaxMind 提供了免費的 IP 地域數據庫,這個數據庫是二進制的,不能用文本編輯器打開,須要上面的 GeoIP 庫來讀取:code

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


配置 Nginx
最後是配置 nginx,在相關地方加上以下的配置就能夠了:vps

# vi /etc/nginx/nginx.conf
...
geoip_country /home/vpsee/GeoIP.dat;

fastcgi_param GEOIP_COUNTRY_CODE $geoip_country_code;
fastcgi_param GEOIP_COUNTRY_CODE3 $geoip_country_code3;
fastcgi_param GEOIP_COUNTRY_NAME $geoip_country_name;
...

 if ($geoip_country_code = CN) {
    root /home/vpsee/cn/;
 }

這樣,當來自中國的 IP 訪問網站後就自動訪問到預約的 /home/vpsee/cn 頁面。關於 Nginx + GeoIP 還有不少有用的用法,好比作個簡單的 CDN,來自中國的訪問自動解析到國內服務器、來自美國的訪問自動轉向到美國服務器等。MaxMind 還提供了全球各個城市的 IP 信息,還能夠下載城市 IP 數據庫來針對不一樣城市作處理。

相關文章
相關標籤/搜索