核心是分层管控连接全生命周期并验证效果:检查worker_connections与系统限制匹配,按IP设limit_conn和limit_req双限流,收紧client_header_timeout等超时参数,启用stub_status配合Prometheus监控验证。

全面审计和加固 Nginx 并发控制基线,核心是防止资源耗尽型攻击(如慢速攻击、连接洪泛),同时保障合法用户的服务可用性。不能只调大数值,而要从连接建立、保持、处理、释放四个阶段做分层管控,并配合可观测性验证效果。
检查当前并发能力与真实负载
先摸清底数,避免盲目调参:
- 执行 nginx -V 查看编译参数,确认是否启用
--with-http_stub_status_module(状态页必需) - 在 server 块中临时启用状态接口:
location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; },再用curl http://localhost/nginx_status观察Active connections、Reading/Writing/Waiting实时分布 - 结合系统级指标:运行
ss -s | grep "TCP:"看 ESTAB 连接总数,对比net.core.somaxconn和net.ipv4.ip_local_port_range是否构成瓶颈 - 查看 access_log 中高频 IP 的请求频率(如每秒请求数 >50 且无合理 User-Agent),识别扫描或爬虫行为
分层设置连接限制策略
单一 limit_conn 往往不够,需组合使用:
-
全局连接数上限:在 http 块中配置
worker_connections 1024;(根据内存调整,建议 ≤ 2048),并匹配系统ulimit -n值 -
按客户端 IP 限流:在 http 块定义共享内存区
limit_conn_zone $binary_remote_addr zone=perip:10m;,再在 server 或 location 中应用limit_conn perip 16;(单 IP 最多 16 并发连接) -
按请求速率限流:搭配
limit_req_zone $binary_remote_addr zone=req_perip:10m rate=10r/s;和limit_req burst=20 nodelay;,防突发请求打满后端 -
关键路径强化保护:对登录、API 接口等敏感 location,叠加更严策略,例如
limit_conn perip 4; limit_req rate=2r/s burst=5;
收紧连接生命周期参数
缩短无效连接占用时间,提升连接周转率:
-
客户端连接超时:设置
client_header_timeout 15s;、client_body_timeout 15s;,防 slowloris 类攻击 -
Keep-Alive 控制:启用但限制
keepalive_timeout 30s;、keepalive_requests 100;,避免长连接堆积 -
读写超时兜底:反向代理场景下,必须配置
proxy_connect_timeout 5s;、proxy_send_timeout 30s;、proxy_read_timeout 30s;,防止上游响应慢拖垮 Nginx -
缓冲区防溢出:设
client_max_body_size 10m;、client_header_buffer_size 1k;、large_client_header_buffers 4 4k;
验证与持续监控
配置生效不等于防护有效,必须验证:
- 用
ab -n 1000 -c 200 https://your-domain.com/模拟压测,观察/nginx_status中 Waiting 连接是否稳定、错误日志有无503或connection refused - 检查 error_log 中是否频繁出现
accept() failed (24: Too many open files),若有则需调高 ulimit 和 somaxconn - 将
limit_conn_status 503;和自定义错误页结合,避免暴露 Nginx 默认提示 - 把
stub_status数据接入 Prometheus + Grafana,监控 Active connections 趋势与阈值偏离度


















