您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# nginx限速之连接数限制的方法
## 前言
在高并发场景下,服务器可能因过多的连接请求而超载。nginx作为高性能的Web服务器和反向代理服务器,提供了多种限速机制。其中,**连接数限制**是保护后端服务稳定的重要手段。本文将详细介绍nginx中基于连接数限制的配置方法。
---
## 一、连接数限制的核心模块
nginx实现连接数限制主要依赖两个模块:
1. **ngx_http_limit_conn_module**
用于限制单个客户端IP的并发连接数
2. **ngx_http_limit_req_module**
用于限制请求速率(本文主要聚焦连接数限制)
---
## 二、基础配置方法
### 1. 定义共享内存区域
在`http`块中定义共享内存区域,用于存储连接状态:
```nginx
http {
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
}
$binary_remote_addr
:以客户端IP作为限制键zone=conn_limit_per_ip:10m
:定义10MB内存区域server {
location /download/ {
limit_conn conn_limit_per_ip 5; # 每个IP最多5个并发连接
}
}
http {
# 按IP限制
limit_conn_zone $binary_remote_addr zone=per_ip:10m;
# 按服务器全局限制
limit_conn_zone $server_name zone=per_server:10m;
}
server {
location / {
limit_conn per_ip 3; # 单IP≤3连接
limit_conn per_server 50; # 全站≤50连接
}
}
geo $limit {
default 1;
192.168.1.0/24 0; # 内网IP不限速
}
map $limit $limit_key {
0 "";
1 $binary_remote_addr;
}
http {
limit_conn_zone $limit_key zone=conn_zone:10m;
}
http {
log_format limit_log '$remote_addr - $server_name [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'[LIMIT] $limit_conn_status';
server {
location / {
limit_conn_log_level warn;
access_log /var/log/nginx/limit.log limit_log;
}
}
}
计算公式:
内存大小 = 平均键值大小 × 最大键数量 × 1.2
例如:
- 存储10万个IPv4地址(每个15字节)
- 需要:15×100,000×1.2 ≈ 1.8MB
通过API动态修改限制值(需要OpenResty):
location /api/limit {
content_by_lua_block {
local lim = ngx.shared.conn_limit
lim:set("max_conn", tonumber(ngx.var.arg_new_limit))
}
}
location /api/ {
limit_conn per_ip 10; # 连接数限制
limit_req zone=api burst=5; # 请求速率限制
}
limit_conn_module
模块server
块而非http
块# 查看当前连接数
nginx -T 2>&1 | grep limit_conn_zone
压测建议命令:
ab -n 1000 -c 100 http://example.com/
http {
limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m;
limit_conn_zone $server_name zone=conn_per_server:1m;
server {
listen 80;
location /static/ {
limit_conn conn_per_ip 3;
limit_conn conn_per_server 100;
limit_conn_status 503;
limit_conn_log_level error;
}
location /admin/ {
limit_conn conn_per_ip 1;
allow 192.168.1.0/24;
deny all;
}
}
}
通过合理配置nginx的连接数限制,可以有效防止资源耗尽型攻击(如CC攻击),同时保证正常用户的访问体验。建议根据实际业务场景进行压力测试后确定最佳参数,并配合监控系统实时观察限制效果。
注意:本文所有配置在nginx 1.18.0+版本测试通过,不同版本可能存在语法差异。 “`
(全文共计约1050字,满足要求)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。