nginx-限制客户端并发数

文章目录


前言

瞬时大量用户访问服务器,导致服务器超载而宕机。

恶意请求攻击服务器,导致服务器超载而宕机。

nginx如何限制每个客户端的并发连接数?


一、ngx_http_limit_conn_module

生效阶段: NGX_HTTP_PREACCESS_PHASE

模块默认编译进nginx,通过--without-http_limit_conn_module禁用。

生效范围:

  • 全部worker进程(基于共享内存)
  • 进入preaccess阶段前不生效
  • 限制的有效性取决于key的设计:依赖postread阶段的realip模块取到真实的IP。
    ngx_http_limit_conn_module官方传送门

二、指令介绍

1. limit_conn_zone

定义共享内存(包含大小),以及key关键字

代码如下(示例):

bash 复制代码
Syntax:	limit_conn_zone key zone=name:size;
Default:	---
Context:	http

2.limit_conn

限制并发连接数

代码如下(示例):

bash 复制代码
Syntax:	limit_conn zone number;
Default:	---
Context:	http, server, location

3. limit_conn_log_level

限制发生时的日志级别

bash 复制代码
Syntax:	limit_conn_log_level info | notice | warn | error;
Default:	
limit_conn_log_level error;
Context:	http, server, location
This directive appeared in version 0.8.18.

4. limit_conn_status

限制发生时向客户端返回的错误码

bash 复制代码
Syntax:	limit_conn_status code;
Default:	
limit_conn_status 503;
Context:	http, server, location
This directive appeared in version 1.3.15.

案例

未限制

现在limit_conn是注释状态

bash 复制代码
[root@test20 nginx]# cat conf.d/limit_conn.conf 
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
	server_name limit_conn.test.io;
        root html/;
	error_log  /var/log/nginx/myerror.log info;        
        location / {
		#limit_conn_status 500;
 		#limit_conn_log_level warn;
		#limit_conn addr 1;
	}
}
# 如上,定义了一个addr的共享区域,用$binary_remote_addr作为key。

# 用ab 压测
ab -c 1000 -n 100000 http://limit_conn.test.io/limit.html

# 查看access.log的内容,分析返回状态码,全部返回200
[root@test20 nginx]# cat /var/log/nginx/access.log | awk -F' ' '{print $9}' | sort | uniq -c
      1 
 100000 200

限制

bash 复制代码
[root@test20 nginx]# cat conf.d/limit_conn.conf 
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
	server_name limit_conn.test.io;
        root html/;
	error_log  /var/log/nginx/myerror.log info;        
        location / {
		limit_conn_status 500;
 		limit_conn_log_level warn;
		limit_conn addr 1;
	}
}
# 如上,定义了一个addr的共享区域,用$binary_remote_addr作为key。

# 用ab 压测
ab -c 1000 -n 100000 http://limit_conn.test.io/limit.html

# 查看access.log的内容,分析返回状态码,有部分返回了500
[root@test20 nginx]# cat /var/log/nginx/access.log | awk -F' ' '{print $9}' | sort | uniq -c
      1 
 170998 200
   2676 500

总结

下一节,介绍nginx限流

相关推荐
熬夜苦读学习38 分钟前
Linux文件系统
linux·运维·服务器·开发语言·后端
荔枝荷包蛋6661 小时前
【网络】高级IO——Reactor版TCP服务器
运维·服务器
GGGGGGGGGGGGGG.2 小时前
hapxory-ACL基础介绍及案例
运维·服务器·网络
黑牛先生2 小时前
【Linux】匿名管道
linux·运维·服务器
流星白龙2 小时前
【Linux】35.封装 UdpSocket(2)
linux·运维·windows
是码农没错了2 小时前
银河麒麟系统安装mysql5.7【亲测可行】
linux·运维·kylin
技术小齐5 小时前
网络运维学习笔记 017HCIA-Datacom综合实验01
运维·网络·学习
大囚长5 小时前
AI工作流+专业知识库+系统API的全流程任务自动化
运维·人工智能·自动化
fajianchen5 小时前
什么是HTTP/2协议?NGINX如何支持HTTP/2并提升网站性能?
nginx·http
Struggle Sheep5 小时前
linux安装redis
linux·运维·redis