插件窝 干货文章 Nginx和GeoIP模块如何读取IP所在的地域信息

Nginx和GeoIP模块如何读取IP所在的地域信息

GeoIP country Nginx 数据库 677    来源:    2025-04-25

使用Nginx和GeoIP模块读取IP地域信息

Nginx结合GeoIP模块可以有效地识别访问者的地理位置信息,这对于内容本地化、访问控制、流量分析等场景非常有用。

安装GeoIP模块

1. 确认Nginx是否已支持GeoIP

nginx -V 2>&1 | grep -o with-http_geoip_module

如果输出with-http_geoip_module,则表示已安装;否则需要重新编译Nginx。

2. 安装GeoIP库

在大多数Linux发行版上:

# Ubuntu/Debian
sudo apt-get install libgeoip-dev

# CentOS/RHEL
sudo yum install geoip-devel

3. 重新编译Nginx(如果需要)

./configure --with-http_geoip_module
make
sudo make install

配置GeoIP数据库

1. 下载GeoIP数据库

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

2. 配置Nginx使用GeoIP数据库

在nginx.conf的http块中添加:

http {
    geoip_country /path/to/GeoIP.dat;
    geoip_city /path/to/GeoLiteCity.dat;
    ...
}

使用GeoIP信息

1. 基本使用示例

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;
    }
}

2. 可用变量

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 - 区号(美国)

3. 高级使用:根据地理位置限制访问

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;
        }
        # 其他配置...
    }
}

使用GeoIP2模块(更新版本)

MaxMind推荐使用GeoIP2数据库格式:

  1. 安装libmaxminddb库:
# Ubuntu/Debian
sudo apt-get install libmaxminddb-dev

# CentOS/RHEL
sudo yum install libmaxminddb-devel
  1. 下载GeoIP2数据库:
wget https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz
tar -zxvf GeoLite2-City.tar.gz
  1. 重新编译Nginx并添加--with-http_geoip2_module

  2. 配置:

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;
    }
}

注意事项

  1. GeoIP数据库需要定期更新以保持准确性
  2. 对于隐私敏感的应用,需考虑GDPR等合规要求
  3. 移动设备和VPN可能会影响GeoIP的准确性
  4. GeoIP2比传统GeoIP提供更精确的数据和更快的查询速度

通过以上配置,Nginx可以有效地利用GeoIP信息来实现基于地理位置的各种功能。