今接到客户需求,杭州的用户访问打开同个域名时显示不同的网站,第一时间想到在nginx负载上做IP限制,操作过程如下
下载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
下载城市数据,还有一个国家数据GeoCountory.data.gz的,这里没用就不下载了,我们直接下载城市数据
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoLiteCity.dat.gz 解压后的数据文件等nginx安装完后copy到nginx的conf目录中
查看下nginx编译的信息 /nginx/sbin/nginx -V
重新编译nginx加上 --with-http-geoip_module
编辑nginx.conf
在http对象内 增加一条 geoip_city /usr/local/webserver/nginx/conf/GeoLiteCity.dat;
如:
http{
[...]
geoip_city /usr/local/webserver/nginx/conf/GeoLiteCity.dat;
server {
[...]
}
}
OK,数据变量有几个参数可以传送给后端
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;
每个server可以通过这些变量来判断,比如要杭州的访问192.168.0.20这个服务器
server{
listen 80;
[...]
location / {
if($geoip_city=Hangzhou) {
proxy_pass http://192.168.0.20;
}