插件窝 干货文章 nginx白名单怎么设置

nginx白名单怎么设置

名单 Nginx 配置 其他 599    来源:    2025-04-07

Nginx 白名单设置指南

在Nginx中设置白名单可以通过多种方式实现,主要取决于你想要限制的内容类型(IP地址、域名、用户代理等)。以下是几种常见的白名单配置方法:

1. IP地址白名单

基于IP限制访问

location / {
    # 允许的IP列表
    allow 192.168.1.1;
    allow 192.168.1.2;
    allow 10.0.0.0/8;

    # 拒绝所有其他IP
    deny all;

    # 其他配置...
}

使用include文件管理IP列表

location / {
    include /etc/nginx/whitelist-ips.conf;
    deny all;

    # 其他配置...
}

然后在/etc/nginx/whitelist-ips.conf文件中:

allow 192.168.1.1;
allow 192.168.1.2;

2. HTTP Referer白名单

location / {
    valid_referers none blocked server_names
               ~.example.com
               ~.trusted-domain.com;

    if ($invalid_referer) {
        return 403;
    }

    # 其他配置...
}

3. 用户代理(User-Agent)白名单

location / {
    if ($http_user_agent !~* "(Googlebot|Bingbot|YandexBot)") {
        return 403;
    }

    # 其他配置...
}

4. 基于GeoIP模块的白名单

首先确保安装了ngx_http_geoip_module模块,然后:

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

    map $geoip_country_code $allowed_country {
        default no;
        US yes;
        CA yes;
        GB yes;
    }

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

            # 其他配置...
        }
    }
}

5. 基于HTTP认证的白名单

location / {
    auth_basic "Restricted Access";
    auth_basic_user_file /etc/nginx/.htpasswd;

    # 其他配置...
}

最佳实践建议

  1. 分层保护:结合多种白名单方法提供多层保护
  2. 定期审查:定期更新白名单列表
  3. 日志监控:记录被拒绝的访问尝试
  4. 测试变更:修改配置前先在测试环境验证
  5. 使用include:将大型白名单列表放在单独文件中便于管理

注意事项

  • 修改配置后记得测试并重载Nginx:nginx -t && nginx -s reload
  • 过于严格的白名单可能会阻止合法用户访问
  • 对于动态IP用户,考虑使用其他认证方式而非IP白名单

需要针对特定场景的白名单配置建议,可以提供更多细节,我可以给出更具体的方案。