插件窝 干货文章 Nginx如何实现基于请求来源地理位置的访问控制配置

Nginx如何实现基于请求来源地理位置的访问控制配置

GeoIP Nginx 配置 访问 326    来源:    2025-04-10

Nginx实现基于地理位置(GeoIP)的访问控制配置

Nginx可以通过GeoIP模块实现基于客户端IP地址的地理位置访问控制。以下是完整的配置步骤:

1. 安装GeoIP模块

首先确保Nginx安装了GeoIP模块:

# 对于Debian/Ubuntu
sudo apt-get install libgeoip1 nginx-module-geoip

# 对于CentOS/RHEL
sudo yum install nginx-module-geoip

2. 下载GeoIP数据库

下载最新的GeoIP数据库:

mkdir -p /usr/share/GeoIP
cd /usr/share/GeoIP
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoIP.dat.gz
gunzip GeoLiteCity.dat.gz

3. 配置Nginx使用GeoIP

在nginx.conf的http块中添加:

http {
    geoip_country /usr/share/GeoIP/GeoIP.dat;
    geoip_city /usr/share/GeoIP/GeoLiteCity.dat;

    # 加载GeoIP模块
    load_module modules/ngx_http_geoip_module.so;

    # 定义变量
    map $geoip_country_code $allowed_country {
        default no;
        US yes;
        CA yes;
        GB yes;
        AU yes;
        # 添加其他允许的国家代码
    }
}

4. 实现访问控制

方法1:允许/阻止特定国家访问

server {
    listen 80;
    server_name example.com;

    if ($allowed_country = no) {
        return 403;
        # 或者重定向到其他页面
        # return 301 http://example.com/blocked.html;
    }

    # 其他配置...
}

方法2:基于国家代码的配置

location / {
    # 只允许美国和加拿大访问
    if ($geoip_country_code !~ ^(US|CA)$) {
        return 403;
    }

    # 其他配置...
}

方法3:使用geo模块更灵活控制

geo $blocked_country {
    default 0;
    # 阻止来自CN和RU的访问
    CN 1;
    RU 1;
}

server {
    listen 80;
    server_name example.com;

    if ($blocked_country) {
        return 403;
    }

    # 其他配置...
}

5. 高级用法:基于城市的访问控制

location / {
    # 只允许来自纽约的用户访问
    if ($geoip_city !~* "New York") {
        return 403;
    }

    # 其他配置...
}

6. 测试和重载配置

sudo nginx -t  # 测试配置
sudo systemctl reload nginx  # 重载配置

注意事项

  1. GeoIP数据库需要定期更新以保持准确性
  2. 基于IP的地理位置识别并非100%准确
  3. 大量使用if条件可能会影响性能
  4. 可以考虑使用Cloudflare等CDN服务的地理位置功能作为替代方案

数据库更新

可以设置cron任务定期更新GeoIP数据库:

0 2 * * 1 wget -qO- http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz | gunzip > /usr/share/GeoIP/GeoIP.dat && service nginx reload

通过以上配置,您可以灵活地基于用户地理位置控制对您网站的访问。