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限流

相关推荐
安红豆.44 分钟前
Linux基础入门 --13 DAY(SHELL脚本编程基础)
linux·运维·操作系统
..空空的人44 分钟前
linux基础指令的认识
linux·运维·服务器
penny_tcf1 小时前
Linux基础命令halt详解
linux·运维·服务器
万界星空科技2 小时前
界星空科技漆包线行业称重系统
运维·经验分享·科技·5g·能源·制造·业界资讯
荣世蓥2 小时前
10.2 Linux_进程_进程相关函数
linux·运维·服务器
gma9992 小时前
【MySQL】服务器管理与配置
运维·服务器
henan程序媛3 小时前
Jenkins Pipline流水线
运维·pipeline·jenkins
安全不再安全3 小时前
Linux 安装 yum
linux·运维·centos
suri ..3 小时前
【Linux】-----进程第二弹(优先级,环境变量)
linux·运维·服务器
Jay-juice4 小时前
Makefile入门
linux·运维·服务器