DDoS防护策略:Linux下Nginx的limit_req与limit_conn调优

155 阅读1分钟

微信图片_20230808094553.png在Linux环境下,Nginx的limit_req和limit_conn模块是防御DDoS攻击的关键工具。前者通过限流控制请求速率,后者通过连接数限制防止资源耗尽。以下结合实际场景,阐述两者的调优策略。

一、 limit_req 模块调优:速率限制****

1. 基础配置
在nginx.conf的http块中定义共享内存区,并在server或location块中应用限流规则:

2. 

nginx

3. 

4. 

 http {
 limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
 }
 server {
 location /api/ {
 limit_req zone=req_limit burst=20 nodelay;
 }
 }

5. 

1. zone=req_limit:10m:分配10MB内存存储IP请求状态,约支持16万独立IP。

2. rate=10r/s:限制每个IP每秒最多10个请求。

3. burst=20:允许突发20个请求进入队列,避免误伤正常用户。

4. nodelay:直接处理队列中的请求(无延迟),若需平滑限流可移除该参数。

6. 动态调整
针对不同业务场景,可通过map指令动态分配限流策略:

7. 

nginx

8. 

9. 

 map httpuseragenthttp_user_agent limit_key {
 default $binary_remote_addr;
 "~*bot" binaryremoteaddrbinary_remote_addrhttp_user_agent; # 爬虫按UA+IP限流
 }
 http {
 limit_req_zone $limit_key zone=req_limit:10m rate=5r/s;
 }

10. 

二、 limit_conn 模块调优:连接数限制****

1. 

全局连接数控制
限制单个IP的并发连接数,防止连接耗尽:

2. 

3. 

nginx

4. 

5. 

 http {
 limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
 }
 server {
 location / {
 limit_conn conn_limit 10; # 每个IP最多10个连接
 }
 }

6. 

7. 

分场景细化
对API接口和静态资源设置不同阈值:

8. 

9. 

nginx

10. 

11. 

 limit_conn_zone $server_name zone=server_conn:10m;
 server {
 limit_conn conn_limit 10;
 location /static/ {
 limit_conn server_conn 100; # 静态资源允许更高并发
 }
 }

12. 

三、综合防护策略****

1. 

协同工作
结合limit_req和limit_conn,例如:

2. 

3. 

nginx

4. 

5. 

 location /api/ {
 limit_req zone=req_limit burst=10;
 limit_conn conn_limit 5;
 }

6. 

既控制请求速率,又限制并发连接数。

7. 

8. 

监控与告警
通过stub_status模块监控Nginx状态:

9. 

10. 

nginx

11. 

12. 

 location /nginx_status {
 stub_status;
 allow 127.0.0.1;
 deny all;
 }

13. 

结合Prometheus+Grafana实时监控active connections和requests per second,动态调整阈值。

14. 

15. 

弹性扩展
在云环境下,可结合Auto Scaling根据负载自动增减Nginx实例,分散DDoS压力。

16. 

通过上述调优,Nginx可有效抵御CC攻击和连接耗尽型DDoS。实际应用中需结合业务流量特征,平衡防护效果与用户体验。