插件窝 干货文章 nginx中如何使用geoip做区域限制

nginx中如何使用geoip做区域限制

GeoIP country Nginx 配置 251    来源:    2025-04-26

使用Nginx GeoIP模块进行区域限制

GeoIP模块允许Nginx根据客户端的IP地址识别其地理位置,从而实现基于区域的访问控制。以下是完整的配置指南:

1. 前提条件

  • 已安装Nginx并支持ngx_http_geoip_module模块
  • 拥有GeoIP数据库文件(如GeoIP.datGeoIP2.dat)

2. 安装GeoIP模块

对于已编译的Nginx

# 安装依赖
sudo apt-get install libgeoip-dev  # Debian/Ubuntu
sudo yum install geoip-devel       # CentOS/RHEL

# 重新编译Nginx添加模块
./configure --with-http_geoip_module
make && make install

使用动态模块(新版本)

sudo apt-get install nginx-module-geoip  # Debian/Ubuntu
sudo yum install nginx-module-geoip      # CentOS/RHEL

然后在nginx.conf中添加:

load_module modules/ngx_http_geoip_module.so;

3. 配置GeoIP数据库

http {
    # 指定GeoIP数据库路径
    geoip_country /usr/share/GeoIP/GeoIP.dat;
    geoip_city /usr/share/GeoIP/GeoLiteCity.dat;

    # 或者对于GeoIP2格式
    geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
        $geoip2_data_country_code country iso_code;
    }
}

4. 基本区域限制配置

允许/阻止特定国家

http {
    # 定义允许的国家代码
    map $geoip_country_code $allowed_country {
        default no;
        US yes;  # 允许美国
        CA yes;  # 允许加拿大
        GB yes;  # 允许英国
    }

    server {
        location / {
            if ($allowed_country = no) {
                return 403;
                # 或者重定向
                # return 301 https://example.com/blocked;
            }

            # 正常处理请求
            proxy_pass http://backend;
        }
    }
}

使用GeoIP2的配置示例

http {
    geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
        $geoip2_data_country_code country iso_code;
    }

    map $geoip2_data_country_code $allowed_country {
        default no;
        US yes;
        CA yes;
    }

    server {
        if ($allowed_country = no) {
            return 403;
        }
    }
}

5. 高级用法

基于城市限制

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

    server {
        location / {
            if ($geoip_city_country_code = CN) {
                if ($geoip_city = "Beijing") {
                    return 403;
                }
            }
        }
    }
}

结合ACL使用

geo $blocked_ip {
    default 0;
    # 特定IP不受区域限制
    192.168.1.100 1;
}

server {
    location / {
        if ($blocked_ip) {
            break;  # 跳过区域检查
        }

        if ($allowed_country = no) {
            return 403;
        }
    }
}

6. 性能优化

  1. 使用内存缓存:将GeoIP数据库加载到内存
  2. 减少数据库查找:只在必要时进行GeoIP查询
  3. 使用最新数据库:定期更新GeoIP数据库

7. 测试配置

nginx -t  # 测试配置
nginx -s reload  # 重载配置

8. 获取GeoIP数据库

可以从以下来源获取GeoIP数据库: - MaxMind官方网站(需注册) - Debian/Ubuntu的geoip-database包 - CentOS/RHEL的GeoIP

注意事项

  1. GeoIP定位并非100%准确
  2. 使用VPN或代理服务器的用户可能绕过限制
  3. 考虑GDPR等隐私法规要求
  4. 对于高流量网站,GeoIP查询可能影响性能

通过以上配置,您可以有效地实现基于地理位置的访问控制,满足业务或合规需求。