插件窝 干货文章 Nginx反向代理中基于ACL的访问控制

Nginx反向代理中基于ACL的访问控制

Nginx 访问 http ACL 31    来源:    2025-04-20

Nginx反向代理中基于ACL的访问控制

概述

在Nginx反向代理配置中,基于访问控制列表(ACL)可以实现精细化的流量控制和安全防护。ACL允许您根据客户端IP、请求头、URI等多种条件来限制或允许访问。

常用ACL配置方法

1. 基于IP地址的访问控制

location / {
    # 允许特定IP或IP段
    allow 192.168.1.0/24;
    allow 10.0.0.1;

    # 拒绝其他所有IP
    deny all;

    proxy_pass http://backend;
}

2. 基于地理位置的访问控制

使用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;
            }
            proxy_pass http://backend;
        }
    }
}

3. 基于HTTP头的访问控制

location / {
    # 检查特定的请求头
    if ($http_user_agent ~* (bot|crawler|spider)) {
        return 403;
    }

    # 检查Referer头
    if ($http_referer !~* ^https://example\.com) {
        return 403;
    }

    proxy_pass http://backend;
}

4. 基于URI路径的访问控制

location ~ ^/admin {
    # 只允许内部网络访问管理界面
    allow 192.168.1.0/24;
    deny all;

    proxy_pass http://backend;
}

5. 基于时间的访问控制

map $time_iso8601 $allowed_time {
    default 0;
    "~^2023-01-01T" 1;  # 特定日期
    "~^T(08|09|10|11|12|13|14|15|16|17):" 1;  # 工作时间
}

server {
    location / {
        if ($allowed_time = 0) {
            return 403 "Service unavailable outside working hours";
        }
        proxy_pass http://backend;
    }
}

高级ACL配置

1. 组合多个条件

location / {
    # 允许来自特定IP或带有特定token的请求
    set $allow_access 0;

    if ($remote_addr ~ ^192\.168\.1\.) {
        set $allow_access 1;
    }

    if ($http_x_access_token = "SECRET_TOKEN") {
        set $allow_access 1;
    }

    if ($allow_access = 0) {
        return 403;
    }

    proxy_pass http://backend;
}

2. 使用外部ACL文件

http {
    # 定义ACL文件路径
    include /etc/nginx/acl/ip_whitelist.conf;

    server {
        location / {
            # 使用外部文件中定义的变量
            if ($whitelisted_ip = 0) {
                return 403;
            }
            proxy_pass http://backend;
        }
    }
}

/etc/nginx/acl/ip_whitelist.conf内容示例:

geo $whitelisted_ip {
    default 0;
    192.168.1.0/24 1;
    10.0.0.1 1;
}

最佳实践

  1. 最小权限原则:只开放必要的访问权限
  2. 分层防护:结合网络层和应用层的ACL
  3. 日志记录:记录被拒绝的访问尝试
  4. 定期审计:定期审查和更新ACL规则
  5. 性能考虑:复杂的ACL规则可能影响性能,需进行测试

调试技巧

  1. 使用$remote_addr记录客户端IP
  2. 添加自定义响应头显示ACL决策
  3. 在测试阶段使用return 200代替return 403来验证规则
location / {
    add_header X-ACL-Decision "Allowed from $remote_addr";
    # 测试规则
    # return 200 "ACL test passed for $remote_addr";

    # 实际规则
    allow 192.168.1.0/24;
    deny all;

    proxy_pass http://backend;
}

通过合理配置Nginx的ACL功能,您可以有效控制反向代理的访问权限,提高系统的安全性。