今接到客戶需求,杭州的用戶訪問打開同個(gè)域名時(shí)顯示不同的網站(zhàn),第一(yī)時(shí)間(jiān)想到在nginx負載上(shàng)做IP限制,操作(zuò)過程如(rú)下(xià)
下(xià)載GeoIP
wget http://geolite.maxmind.com/download/geoip/api/c/GeoIP.tar.gz
tar zxvf GeoIP.tar.gz
cd GeoIP
cd GeoIP-1.4.8
./configure
make && make install
echo '/usr/local/lib' > /etc/ld.so.conf.d/geoip.conf
ldconfig
下(xià)載城市(shì)數據,還有一(yī)個(gè)國家數據GeoCountory.data.gz的,這(zhè)裏沒用就(jiù)不下(xià)載了(le),我們直接下(xià)載城市(shì)數據
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoLiteCity.dat.gz 解壓後的數據文件等nginx安裝完後copy到nginx的conf目錄中
查看下(xià)nginx編譯的信息 /nginx/sbin/nginx -V
重新(xīn)編譯nginx加上(shàng) --with-http-geoip_module
編輯nginx.conf
在http對象内 增加一(yī)條 geoip_city /usr/local/webserver/nginx/conf/GeoLiteCity.dat;
如(rú):
http{
[...]
geoip_city /usr/local/webserver/nginx/conf/GeoLiteCity.dat;
server {
[...]
}
}
OK,數據變量有幾個(gè)參數可以傳送給後端
proxy_set_header GEOIP-CITY-COUNTRY-CODE3 $geoip_city_country_code3;
proxy_set_header GEOIP-CITY-COUNTRY-NAME $geoip_city_country_name;
proxy_set_header GEOIP-REGION $geoip_region;
proxy_set_header GEOIP-CITY $geoip_city;
proxy_set_header GEOIP-POSTAL-CODE $geoip_postal_code;
proxy_set_header GEOIP-CITY-CONTINENT_CODE $geoip_city_continent_code;
proxy_set_header GEOIP-LATITUDE $geoip_latitude;
proxy_set_header GEOIP-LONGITUDE $geoip_longitude;
每個(gè)server可以通過這(zhè)些(xiē)變量來(lái)判斷,比如(rú)要杭州的訪問192.168.0.20這(zhè)個(gè)服務(wù)器(qì)
server{
listen 80;
[...]
location / {
if($geoip_city=Hangzhou) {
proxy_pass http://192.168.0.20;
}