插件窝 干货文章 Nginx反向代理中基于代理IP的ACL配置

Nginx反向代理中基于代理IP的ACL配置

Nginx ACL proxy server 675    来源:    2025-04-20

Nginx反向代理中基于代理IP的ACL配置

在Nginx反向代理配置中,基于客户端IP地址进行访问控制(ACL)是一项常见的安全需求。以下是几种实现方式:

1. 基本IP访问控制

使用allowdeny指令

location / {
    deny  192.168.1.1;       # 拒绝特定IP
    allow 192.168.1.0/24;    # 允许特定子网
    allow 10.1.1.0/16;       # 允许另一个子网
    deny  all;               # 拒绝所有其他IP
    proxy_pass http://backend;
}

2. 使用geo模块创建IP分组

geo $acl {
    default         0;
    192.168.1.0/24 1;
    10.0.0.0/8     1;
    172.16.0.0/12  1;
}

server {
    location / {
        if ($acl = 0) {
            return 403;  # 禁止访问
        }
        proxy_pass http://backend;
    }
}

3. 结合map模块的复杂ACL

map $remote_addr $acl {
    default          "deny";
    "192.168.1.100" "allow";
    "10.0.0.0/8"     "allow";
}

server {
    location / {
        if ($acl = "deny") {
            return 403;
        }
        proxy_pass http://backend;
    }
}

4. 基于X-Forwarded-For头的ACL

当Nginx前面还有代理层时,需要检查X-Forwarded-For头:

# 提取真实客户端IP
map $http_x_forwarded_for $real_ip {
    default          $remote_addr;
    ~^([^,]+)        $1;
}

geo $acl {
    default         0;
    192.168.1.0/24 1;
    include /etc/nginx/conf.d/ip_whitelist.conf;
}

server {
    location / {
        if ($acl = 0) {
            return 403;
        }
        proxy_pass http://backend;
    }
}

5. 使用ngx_http_geoip_module模块

对于基于地理位置的ACL:

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;
        }
    }
}

最佳实践建议

  1. IP白名单优于黑名单:默认拒绝所有,只允许特定IP
  2. 维护单独的配置文件:将IP列表放在单独文件中便于管理
  3. 考虑性能影响:大量IP规则会影响性能,考虑使用CIDR表示法
  4. 日志记录:记录被拒绝的访问尝试
  5. 动态更新:考虑使用Lua脚本或API动态更新ACL规则

完整示例配置

# /etc/nginx/conf.d/acl.conf
geo $acl {
    default         0;
    include /etc/nginx/conf.d/ip_whitelist.conf;
}

# /etc/nginx/conf.d/ip_whitelist.conf
192.168.1.0/24 1;
10.0.0.0/8     1;

# nginx server配置
server {
    listen 80;
    server_name example.com;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    location / {
        if ($acl = 0) {
            access_log /var/log/nginx/denied.log;
            return 403;
        }

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://backend_servers;
    }
}

通过以上配置,您可以灵活地实现基于IP地址的访问控制,保护您的反向代理服务。