- config: 反向代理、缓存、负载均衡、安全、SSL 等配置模板 - lua: API 网关、认证、动态路由、限流、WebSocket 等脚本示例 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
92 lines
2.6 KiB
Plaintext
92 lines
2.6 KiB
Plaintext
# ============================================================
|
|
# Nginx 连接数限制配置示例
|
|
# ============================================================
|
|
#
|
|
# 功能说明:
|
|
# - 限制单 IP 并发连接数
|
|
# - 防止连接耗尽攻击
|
|
# - 保护后端服务
|
|
#
|
|
# Lolly 对应配置:
|
|
# server:
|
|
# max_conns_per_ip: 100 # 单 IP 最大连接数
|
|
# security:
|
|
# rate_limit:
|
|
# conn_limit: 50 # 连接数限制
|
|
# ============================================================
|
|
|
|
http {
|
|
# 连接限制区域定义
|
|
# Lolly 对应: security.rate_limit.conn_limit
|
|
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
|
|
|
|
# 基于服务器的连接限制
|
|
limit_conn_zone $server_name zone=server_conn:10m;
|
|
|
|
server {
|
|
listen 80;
|
|
server_name connlimit.example.com;
|
|
|
|
# 单 IP 最大连接数
|
|
# Lolly 对应: max_conns_per_ip: 50
|
|
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
|
|
limit_conn conn_limit 50;
|
|
|
|
# 限制时返回的状态码
|
|
limit_conn_status 503;
|
|
|
|
# 全局连接限制(服务器级别)
|
|
# limit_conn server_conn 1000;
|
|
|
|
location /download {
|
|
#下载接口更严格的连接限制
|
|
limit_conn conn_limit 10;
|
|
|
|
proxy_pass http://backend:8080;
|
|
}
|
|
|
|
# WebSocket 连接限制(需要单独处理)
|
|
location /ws {
|
|
# WebSocket 长连接,允许更多
|
|
limit_conn conn_limit 20;
|
|
|
|
proxy_pass http://websocket:8080;
|
|
proxy_http_version 1.1;
|
|
proxy_set_header Upgrade $http_upgrade;
|
|
proxy_set_header Connection "upgrade";
|
|
}
|
|
|
|
# 连接限制错误页面
|
|
error_page 503 = @conn_limit_error;
|
|
location @conn_limit_error {
|
|
default_type application/json;
|
|
return 503 '{"error": "Connection limit exceeded"}';
|
|
}
|
|
}
|
|
}
|
|
|
|
# 连接限制说明:
|
|
#
|
|
# 1. 工作原理:
|
|
# - 统计每个 IP 的活跃连接数
|
|
# - 超过限制时拒绝新连接
|
|
# - 连接关闭后计数减少
|
|
#
|
|
# 2. 与速率限制区别:
|
|
# - 速率限制: 控制请求频率
|
|
# - 连接限制: 控制并发连接数
|
|
# - 两者互补使用
|
|
#
|
|
# 3. 适用场景:
|
|
# - 大文件下载(限制并发下载)
|
|
# - WebSocket 连接(限制长连接)
|
|
# - 防止连接耗尽攻击
|
|
#
|
|
# 4. 配置建议:
|
|
# - 普通请求: 50-100 连接/IP
|
|
# - 下载接口: 5-10 连接/IP
|
|
# - WebSocket: 10-20 连接/IP
|
|
#
|
|
# 5. Lolly 配置:
|
|
# - max_conns_per_ip: 全局连接限制
|
|
# - security.rate_limit.conn_limit: 安全模块连接限制 |