1.下载ip数据库
GeoIP.dat.gz
GeoLiteCity.dat.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
2.下载安装nginx
这里使用tengine 可以动态添加模块
下载和安装就不多说了
这里注意一下安装时添加geoip模块
这里会有一个报错需要添加Geoip的库
安装依赖
rpm -Uvh GeoIP-devel-1.5.1-5.el6.x86_64.rpm
rpm -Uvh GeoIP-1.5.1-5.el6.x86_64.rpm
./configure --prefix=/usr/local/nginx_geoip --with-pcre=/root/pcre-8.36 --with-http_gzip_static_module --with-http_geoip_module
make
make install
gunzip -d GeoIP.dat.gz#国家数据库
mv GeoLiteCity.dat.gz /usr/local/nginx_geoip/conf/
gunzip -d GeoLiteCity.dat.gz#城市数据库
mv GeoLiteCity.dat /usr/local/nginx_geoip/conf/
3.nginx.conf配置
在http段中添加
http {
....................
geoip_city GeoLiteCity.dat;
geoip_country GeoIP.dat;
#日志添加地理位置信息'$geoip_country_name $geoip_region $geoip_city'
log_format access '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"' '$geoip_country_name $geoip_region $geoip_city';
}
server段中
以下是根据地域来转发
server {
listen 9999;
server_name _;
#charset koi8-r;
access_log logs/host.access.log access;
location / {
# root html;
# index index.html index.htm;
#省份代码geoip_region geoip_city是城市名,例如$geoip_region ~ "Chengdu"
if ($geoip_region ~ "22") {
proxy_pass http://www.lashou.com;
}
#根据某个ip进行转发
if ($remote_addr ~ "192.168.1.100"){
proxy_pass http://www.baidu.com;
}
}
以下是geoip_region的省份代码
CN,01,"Anhui"
CN,02,"Zhejiang"
CN,03,"Jiangxi"
CN,04,"Jiangsu"
CN,05,"Jilin"
CN,06,"Qinghai"
CN,07,"Fujian"
CN,08,"Heilongjiang"
CN,09,"Henan"
CN,10,"Hebei"
CN,11,"Hunan"
CN,12,"Hubei"
CN,13,"Xinjiang"
CN,14,"Xizang"
CN,15,"Gansu"
CN,16,"Guangxi"
CN,18,"Guizhou"
CN,19,"Liaoning"
CN,20,"Nei Mongol"
CN,21,"Ningxia"
CN,22,"Beijing"
CN,23,"Shanghai"
CN,24,"Shanxi"
CN,25,"Shandong"
CN,26,"Shaanxi"
CN,28,"Tianjin"
CN,29,"Yunnan"
CN,30,"Guangdong"
CN,31,"Hainan"
CN,32,"Sichuan"
CN,33,"Chongqing"
当不确定具体是否有城市名可以用strings命令查看字符串,比如:
strings GeoLiteCity.dat |grep -i beijing
这样就匹配到了 Beijing,所以我们可以用 Beijing这个城市名。
验证:
if ($geoip_city ~ "Chengdu") {
proxy_pass http://www.lashou.com;
}
如果是解析出来是成都就转发到拉手网上
这里可以看到是北京的ip所以没有转发到拉手网去
修改配置
if ($geoip_city ~ "Beijing") {
proxy_pass http://www.lashou.com;
}
这里就看出北京的ip就转发到了拉手网
这样就实现不同地理位置ip代理至不同服务器