Nginx结合GeoIP模块可以有效地识别访问者的地理位置信息,这对于内容本地化、访问控制、流量分析等场景非常有用。
nginx -V 2>&1 | grep -o with-http_geoip_module
如果输出with-http_geoip_module
,则表示已安装;否则需要重新编译Nginx。
在大多数Linux发行版上:
# Ubuntu/Debian
sudo apt-get install libgeoip-dev
# CentOS/RHEL
sudo yum install geoip-devel
./configure --with-http_geoip_module
make
sudo make install
MaxMind提供免费和付费的GeoIP数据库:
# 下载国家数据库
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gunzip GeoIP.dat.gz
# 下载城市数据库(更详细)
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoLiteCity.dat.gz
在nginx.conf的http块中添加:
http {
geoip_country /path/to/GeoIP.dat;
geoip_city /path/to/GeoLiteCity.dat;
...
}
server {
location / {
# 设置变量
set $country $geoip_country_code;
set $city $geoip_city;
# 根据国家重定向
if ($geoip_country_code = CN) {
return 301 http://cn.example.com;
}
# 记录访问日志
access_log /var/log/nginx/access.log geoip;
}
}
GeoIP模块提供了多个变量:
国家信息:
$geoip_country_code
- 国家代码(如CN, US)$geoip_country_code3
- 3字母国家代码(如CHN, USA)$geoip_country_name
- 国家全名城市信息:
$geoip_city
- 城市名$geoip_city_continent_code
- 大陆代码$geoip_region
- 地区/州代码$geoip_region_name
- 地区/州全名$geoip_postal_code
- 邮政编码位置信息:
$geoip_latitude
- 纬度$geoip_longitude
- 经度$geoip_dma_code
- DMA代码(美国)$geoip_area_code
- 区号(美国)geoip_country /path/to/GeoIP.dat;
map $geoip_country_code $allowed_country {
default no;
US yes;
GB yes;
CA yes;
}
server {
location / {
if ($allowed_country = no) {
return 403;
}
# 其他配置...
}
}
MaxMind推荐使用GeoIP2数据库格式:
# Ubuntu/Debian
sudo apt-get install libmaxminddb-dev
# CentOS/RHEL
sudo yum install libmaxminddb-devel
wget https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz
tar -zxvf GeoLite2-City.tar.gz
重新编译Nginx并添加--with-http_geoip2_module
配置:
http {
geoip2 /path/to/GeoLite2-City.mmdb {
$geoip2_data_country_code country iso_code;
$geoip2_data_country_name country names en;
$geoip2_data_city_name city names en;
}
}
通过以上配置,Nginx可以有效地利用GeoIP信息来实现基于地理位置的各种功能。