Nginx 的 limit_conn_status 仅能设置连接超限时的 HTTP 状态码(如 429),无法直接自定义响应体;需配合 error_page 指令映射到 internal location,并用 return 返回 JSON 或 HTML 内容。

Nginx 的 limit_conn_status 指令本身**不能直接自定义错误响应体内容**(比如返回 JSON 或 HTML),它只用于设置连接数超限时返回的 HTTP 状态码(默认是 503)。真正实现“自定义错误响应信息”,需要结合 error_page 和 location 块来重写响应体。
1. 正确配置 limit_conn_status 设置状态码
该指令必须放在 http、server 或 location 块中,且需配合 limit_conn 使用。例如:
http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
<pre class="brush:php;toolbar:false;">server {
listen 80;
server_name example.com;
limit_conn addr 10;
limit_conn_status 429; # 超限时返回 429 Too Many Requests
location /api/ {
proxy_pass http://backend;
}
}
}
2. 用 error_page 捕获并重定向到自定义响应位置
将指定状态码(如 429)映射到一个内部 location,由该 location 输出你想要的内容:
server {
# ... 上面的 limit_conn 配置保持不变
<pre class="brush:php;toolbar:false;"># 捕获 limit_conn 触发的 429 状态码
error_page 429 = @rate_limited;
location @rate_limited {
internal; # 确保只能内部跳转,禁止外部直接访问
add_header Content-Type "application/json; charset=utf-8";
return 429 '{"error":"Too many connections","code":429,"message":"You have exceeded the allowed concurrent connections."}';
}
}
3. 可选:返回 HTML 页面或重定向到友好提示页
如果需要更丰富的提示,可返回静态 HTML 或重定向:
- 返回内联 HTML:
limit_conn_status 429










