LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

nginx设置ip白名单与黑名单,敲重点

admin
2025年7月21日 8:8 本文热度 108

完整示例使用了日志格式化 json,方便查看业务日志与各种日志收集。

下面介绍功能作用,两种方法实现
Nginx Geo模块设置与map模块设置的优缺点

目录:

一、geo模块完整示例

二、ip地址太多了改成文件引入形式

三、map模块完整示例

四、扩展:有了白名单的允许还要黑名单干嘛?


两种方案的比较

特性

方案一(文件引入)

方案二(直接map)

性能

更高(使用geo模块)

较低

IP数量支持

支持大量IP

适合少量IP

维护性

更好(分离文件)

一般

CIDR支持

完整支持

需要正则表达式

多层代理处理

更完善

一般

黑白名单逻辑分离

合并处理

推荐使用方案一(文件引入形式),因为:


    1.性能更好,适合大量IP规则

    2.维护更方便,IP列表可以单独管理

    3.支持CIDR格式,更规范

    4.黑白名单逻辑分离,更清晰

    5.多层代理处理更完善



    一、geo模块完整示例

    1. 主配置文件 /usr/local/nginx/conf/nginx.conf

    user www www;worker_processes 4;error_log /data/logs/nginx/error.log;events {    worker_connections 10240;}http {    include       mime.types;    default_type  application/octet-stream;    charset utf-8;    log_format  main  '$remote_addr - $remote_user [$time_local"$request" '        '$status $body_bytes_sent "$http_referer" '        '"$http_user_agent" "$http_x_forwarded_for"';    log_format web_log_json escape=json '{"@timestamp":"$time_iso8601", '                '"remoteIP":"$remote_addr", '                '"clientIP":"$http_x_forwarded_for", '            '"logTime":"$time_local", '            '"uri":"$uri", '            '"requestURI":"$request_uri", '            '"requestMethod":"$request_method", '            '"httpMethod":"$scheme", '            '"status":$status, '            '"servername":"$host", '            '"upstream_name":"$proxy_host", '            '"upstream_addr":"$upstream_addr", '            '"upstream_status":$upstream_status, '            '"upstream_response_time":$upstream_response_time, '            '"responseBytes":$body_bytes_sent, '            '"requestBytes":$request_length, '            '"responseTime":$request_time, '            '"referer":"$http_referer", '            '"userAgent":"$http_user_agent"}';    log_format  web_log  '$remote_addr - $remote_user [$time_local"$request" '        '$status $body_bytes_sent "$http_referer" '        '$host $proxy_host $upstream_addr $upstream_status $upstream_response_time $args'        '"$http_user_agent" "$http_x_forwarded_for"';    sendfile        on;    keepalive_timeout 180;    client_header_buffer_size 128k;    client_max_body_size 2560M;    large_client_header_buffers 4 128k;    proxy_read_timeout 180;    proxy_connect_timeout 180;    server_names_hash_max_size 2048;    server_names_hash_bucket_size 128;        proxy_max_temp_file_size 2048m;    # WebSocket支持    map $http_upgrade $connection_upgrade {        default upgrade;        '' close;    }    # 真实客户端IP提取(处理多层代理如阿里云CLB)    map $http_x_forwarded_for $real_client_ip {        # 提取第一个IP(最左边的IP是客户端真实IP)        ~^([^,]+$1;        # 如果没有XFF头,使用remote_addr        default $remote_addr;    }    # 白名单配置 - 使用geo模块(高性能IP匹配)    geo $whitelist {        default 0;
            # 您原有的IP段(转换为CIDR格式)        113.201.50.0/24 1;        123.139.52.0/24 1;        222.91.198.0/24 1;        117.22.144.0/24 1;        125.76.162.0/24 1;        125.76.161.0/24 1;        125.76.177.0/24 1;        125.76.163.0/24 1;
            # 可以添加更多IP或网段        # 10.10.50.0/24 1;    }    # 黑名单配置 - 使用geo模块    geo $blacklist {        default 0;
            # 您原有的黑名单IP        218.90.199.0/24 1;        58.222.32.0/24 1;        58.222.26.0/24 1;        58.222.25.0/24 1;    }    # 访问控制逻辑    map $real_client_ip $access_control {        # 如果在黑名单中,拒绝        ~ $blacklist 1 { return 403; }
            # 如果不在白名单中,拒绝        ~ $whitelist 0 { return 403; }
            # 默认允许        default 1;    }    # 包含虚拟主机配置    include /usr/local/nginx/conf/vhost/*.conf;}

    虚拟主机配置示例(vhost/example.conf)

    server {    listen 80;    server_name example.com;
        access_log /data/logs/nginx/example.access.log web_log_json;    error_log /data/logs/nginx/example.error.log;
        # 静态文件服务    location /static/ {        alias /data/www/example/static/;        expires 30d;        access_log off;    }
        # 动态请求处理    location / {        # 访问控制(由主配置中的map规则处理)        # 不需要显式if判断,403会自动返回
            # 代理设置        proxy_pass http://backend_servers;        proxy_set_header Host $host;        proxy_set_header X-Real-IP $real_client_ip;        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;        proxy_set_header X-Forwarded-Proto $scheme;
            # 连接设置        proxy_connect_timeout 60s;        proxy_read_timeout 60s;        proxy_send_timeout 60s;
            # 缓冲区设置        proxy_buffer_size 128k;        proxy_buffers 4 256k;        proxy_busy_buffers_size 256k;    }
        # 健康检查端点    location /health {        access_log off;        return 200 "OK";    }}# 上游服务器配置upstream backend_servers {    server 10.0.0.1:8080 weight=5;    server 10.0.0.2:8080 weight=5;    keepalive 32;}

    二、ip地址太多了改成文件引入形式

    1. 主配置文件 /usr/local/nginx/conf/nginx.conf

    user www www;worker_processes 4;error_log /data/logs/nginx/error.log;events {    worker_connections 10240;}http {    include       mime.types;    default_type  application/octet-stream;    charset utf-8;    # 日志格式(保持原有)    log_format  main  '$remote_addr - $remote_user [$time_local"$request" '        '$status $body_bytes_sent "$http_referer" '        '"$http_user_agent" "$http_x_forwarded_for"';
        log_format web_log_json escape=json '{"@timestamp":"$time_iso8601", '                '"remoteIP":"$remote_addr", '                '"clientIP":"$http_x_forwarded_for", '                '"logTime":"$time_local", '                '"uri":"$uri", '                '"requestURI":"$request_uri", '                '"requestMethod":"$request_method", '                '"httpMethod":"$scheme", '                '"status":$status, '                '"servername":"$host", '                '"upstream_name":"$proxy_host", '                '"upstream_addr":"$upstream_addr", '                '"upstream_status":$upstream_status, '                '"upstream_response_time":$upstream_response_time, '                '"responseBytes":$body_bytes_sent, '                '"requestBytes":$request_length, '                '"responseTime":$request_time, '                '"referer":"$http_referer", '                '"userAgent":"$http_user_agent"}';    sendfile        on;    keepalive_timeout 180;    client_header_buffer_size 128k;    client_max_body_size 2560M;    large_client_header_buffers 4 128k;    proxy_read_timeout 180;    proxy_connect_timeout 180;    server_names_hash_max_size 2048;    server_names_hash_bucket_size 128;        proxy_max_temp_file_size 2048m;    # WebSocket支持    map $http_upgrade $connection_upgrade {        default upgrade;        '' close;    }    # 真实客户端IP提取    map $http_x_forwarded_for $real_client_ip {        ~^([^,]+$1;        default $remote_addr;    }    # 白名单配置 - 从外部文件加载    geo $whitelist {        default 0;        include /usr/local/nginx/conf/whitelist_ips.conf;    }    # 黑名单配置 - 从外部文件加载    geo $blacklist {        default 0;        include /usr/local/nginx/conf/blacklist_ips.conf;    }    # 访问控制逻辑    map $real_client_ip $access_control {        ~ $blacklist 1 { return 403; }        ~ $whitelist 0 { return 403; }        default 1;    }    include /usr/local/nginx/conf/vhost/*.conf;}

    2. 白名单IP文件 /usr/local/nginx/conf/whitelist_ips.conf

    # 白名单IP列表113.201.50.0/24 1;123.139.52.0/24 1;222.91.198.0/24 1;117.22.144.0/24 1;125.76.162.0/24 1;125.76.161.0/24 1;125.76.177.0/24 1;125.76.163.0/24 1;# 可以继续添加更多IP...

    3. 黑名单IP文件 /usr/local/nginx/conf/blacklist_ips.conf

    # 黑名单IP列表218.90.199.0/24 1;58.222.32.0/24 1;58.222.26.0/24 1;58.222.25.0/24 1;# 可以继续添加更多IP...

    三、map模块完整示例

    1. 主配置文件 /usr/local/nginx/conf/nginx.conf

    $ cat  /usr/local/nginx/conf/nginx.confuser  www www;worker_processes  4;error_log   /data/logs/nginx/error.log;#error_log  logs/error.log  notice;#error_log  logs/error.log  info;#pid        logs/nginx.pid;events {    worker_connections  10240;}http {    include       mime.types;    default_type  application/octet-stream;        charset utf-8;    log_format  main  '$remote_addr - $remote_user [$time_local"$request" '        '$status $body_bytes_sent "$http_referer" '        '"$http_user_agent" "$http_x_forwarded_for"';    log_format web_log_json escape=json '{"@timestamp":"$time_iso8601", '                '"remoteIP":"$remote_addr", '                '"clientIP":"$http_x_forwarded_for", '            '"logTime":"$time_local", '            '"uri":"$uri", '            '"requestURI":"$request_uri", '            '"requestMethod":"$request_method", '            '"httpMethod":"$scheme", '            '"status":$status, '            '"servername":"$host", '            '"upstream_name":"$proxy_host", '            '"upstream_addr":"$upstream_addr", '            '"upstream_status":$upstream_status, '            '"upstream_response_time":$upstream_response_time, '            '"responseBytes":$body_bytes_sent, '            '"requestBytes":$request_length, '            '"responseTime":$request_time, '            '"referer":"$http_referer", '            '"userAgent":"$http_user_agent"}';    log_format  web_log  '$remote_addr - $remote_user [$time_local"$request" '        '$status $body_bytes_sent "$http_referer" '        '$host $proxy_host $upstream_addr $upstream_status $upstream_response_time $args'        '"$http_user_agent" "$http_x_forwarded_for"';    sendfile        on;        #server_tokens   off;    keepalive_timeout  180;        client_header_buffer_size 128k;        client_max_body_size 2560M;        large_client_header_buffers 4 128k;        proxy_read_timeout 180;        proxy_connect_timeout 180;        server_names_hash_max_size 2048;        server_names_hash_bucket_size 128;            proxy_max_temp_file_size 2048m;        map $http_upgrade $connection_upgrade {        default upgrade;        '' close;    }
        # 真实客户端IP提取    map $http_x_forwarded_for $real_client_ip {        ~^([^,]+$1;        default $remote_addr;    }    # 访问控制逻辑    map $real_client_ip $access_control {        ~ $blacklist 1 { return 403; }        ~ $whitelist 0 { return 403; }        default 1;    }
           #访问白名单控制       map $http_x_forwarded_for $accessip {          default false;          #10.10.50.0/24(网段匹配)          ~*113.201.50true;          ~*123.139.52true;          ~*222.91.198true;          ~*117.22.144true;          ~*125.76.162true;          ~*125.76.161true;          ~*125.76.177true;          ~*125.76.163true;       }       #访问黑名单控制       map $http_x_forwarded_for $denyip {          default true;          #10.10.50.0/24(网段匹配)          ~*218.90.199false;          ~*58.222.32false;          ~*58.222.26false;          ~*58.222.25false;       }    include  /usr/local/nginx/conf/vhost/*.conf;      }

    虚拟主机配置示例(两种方案通用)

    server {    listen 80;    server_name example.com;
        access_log /data/logs/nginx/example.access.log web_log_json;    error_log /data/logs/nginx/example.error.log;
        # geo的使用方式    # if ($access_control = 0) { return 403; }
        # map的使用方式    if ($allow_access = 0) {         # 记录拒绝访问日志        #access_log /usr/local/nginx/logs/access_denied.log main;        return 403 "Forbidden"    }
        location / {        proxy_pass http://backend_servers;        proxy_set_header Host $host;        proxy_set_header X-Real-IP $remote_addr;        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    }
        location /static/ {        alias /data/www/static/;        expires 30d;    }}upstream backend_servers {    server 10.0.0.1:8080;    server 10.0.0.2:8080;}
    四、扩展:有了白名单的允许还要黑名单干嘛?

    白名单与黑名单的协同作用:深入解析访问控制策略

    双名单机制的核心价值

    当您看到同时存在白名单和黑名单配置时,这代表了分层安全策略,它们协同工作实现更精细的访问控制:

    map $http_x_forwarded_for $accessip # 白名单    default false;    ~*113.201.50true# 允许整个IP段    ...}
    map $http_x_forwarded_for $denyip # 黑名单    default true;    ~*218.90.199false# 允许特定IP段    ...}

    分层安全机制的意义

    控制层
    作用
    示例场景
    白名单
    允许访问的基础规则
    只允许公司办公室IP访问系统
    黑名单
    白名单基础上的例外规则
    在允许的办公室IP中,阻止被入侵的特定终端

    双名单协同工作的典型场景

    场景1:白名单基础上的风险IP排除

    # 服务器配置location / {    # 第一层:白名单检测    if ($accessip = false) {        return 403# 拒绝非白名单IP    }
        # 第二层:黑名单检测    if ($denyip = true) {        return 403# 拒绝黑名单IP(即使它在白名单中)    }
        # 其他业务处理...}
    逻辑流程
    1. 请求进入2. 检查是否在白名单中?   → 否:立即拒绝   → 是:继续下一步3. 检查是否在黑名单中?   → 是:拒绝访问(优先级高于白名单)   → 否:允许访问

    场景2:特殊权限分配(白名单中的例外)

    # 只对特定IP开放管理员功能location /admin {    # 所有白名单IP可访问普通功能    if ($accessip = false) { return 403; }
        # 但仅特定非黑名单IP可访问管理员功能    if ($denyip = true) {         return 403 "Admin access restricted"    }
        # 管理员专属处理...}

    为什么不只用白名单?

    单一白名单的局限性及双名单解决方案:

    问题
    白名单单独使用
    白名单+黑名单方案
    白名单IP被入侵
    无法阻止受损IP
    可立即加入黑名单阻断
    IP地址重用风险
    ISP重用IP导致误授权
    黑名单拦截可疑新用户
    临时权限需求
    需修改白名单,影响所有授权IP
    仅通过黑名单解除限制
    异常行为检测
    仅能完全允许或完全拒绝
    允许访问但限制高危操作

    先进用法:动态安全策略

    结合实时威胁情报

    # 动态加载威胁情报map $http_x_forwarded_for $threat_intel {    default 0;    include /etc/nginx/threat-feeds/*.conf;}
    # 在访问控制中应用location / {    # 基础白名单检查    if ($accessip = false) { return 403; }
        # 威胁情报黑名单(优先于普通黑名单)    if ($threat_intel) {        log security_alert "Blocked known threat actor: $http_x_forwarded_for";        return 444# 静默断开连接    }
        # 本地黑名单检查    if ($denyip = true) { return 403; }}

    基于行为的智能拦截

    # 速率限制异常IPlimit_req_zone $http_x_forwarded_for zone=perip:10m rate=10r/s;
    location /login {    # 白名单基础访问    if ($accessip = false) { return 403; }
        # 对高频率访问IP应用严格验证    limit_req zone=perip burst=20 nodelay;
        # 黑名单中的IP直接拒绝    if ($denyip = true) { return 403; }
        # 正常登录处理...}

    何时应该使用双名单?

    双名单策略特别适用于:

    1. 高安全要求系统(如金融、医疗系统)
    2. 企业内网中需要部门隔离的场景
    3. 存在远程办公或第三方访问的系统
    4. 云环境中的多租户应用
    5. 曾经遭遇针对性攻击的业务

    总结

    白名单(allowlist)和黑名单(denylist)不是相互替代,而是深度防御体系中的互补层级

    • 白名单确立最小特权基础:"默认拒绝,显式允许"
    • 黑名单实现动态防御:"允许中排除,按需阻断"

    这种双重机制在复杂网络环境中提供了更灵活的访问控制能力,特别是在企业安全、云原生应用和合规要求严格的场景中具有独特价值。有效的安全策略应像洋葱一样多层防护,而不是单一的硬壳。


    阅读原文:原文链接


    该文章在 2025/7/21 10:16:56 编辑过
    关键字查询
    相关文章
    正在查询...
    点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
    点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
    点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
    点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
    Copyright 2010-2025 ClickSun All Rights Reserved