1. 程式人生 > >3. nginx + http_geoip_module 實現根據 ip 來做不同的處理

3. nginx + http_geoip_module 實現根據 ip 來做不同的處理

文章目錄


如果想遮蔽某個地區的 IP 訪問的話, 用 iptables 把來自某個國家的 IP 重定向到預定頁面不是特別靈活的辦法,如果只有一個 IP 可用而有多個網站在同一 VPS 上怎麼辦?用 iptable 遮蔽某個網站的話也會遮蔽同一 VPS 上的其他網站的訪問。所以正統的辦法還是用 GeoIP 配合對應的 web 伺服器模組,比如:apache + mod_geoip 或者 nginx + http_geoip_module 等。

安裝 Nginx

因為要用到 http_geoip_module 模組,系統自帶的 nginx 一般不帶這個模組,所以要下載 nginx 原始碼後自行編譯:

# 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 庫:

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

下載 IP 資料庫

MaxMind 提供了免費的 IP 地域資料庫,這個資料庫是二進位制的,不能用文字編輯器開啟,需要上面的 GeoIP 庫來讀取:

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

配置 Nginx

最後是配置 nginx,在相關地方加上如下的配置就可以了:

# vi /etc/nginx/nginx.conf

http {
...
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;
...
}

server {
...
        location / {
            root   /home/vpsee/www;
            if ($geoip_country_code = CN) {
                root /home/vpsee/cn;
            }
            ...
        }
...
}

這樣,當來自中國的 IP 訪問網站後就自動訪問到預定的 /home/vpsee/cn 頁面。關於 Nginx + GeoIP 還有很多有用的用法,比如做個簡單的 CDN,來自中國的訪問自動解析到國內伺服器、來自美國的訪問自動轉向到美國伺服器等。MaxMind 還提供了全球各個城市的 IP 資訊,還可以下載城市 IP 資料庫來針對不同城市做處理。