bigywater.tech
常见报错 · 36

Nginx 413 Request Entity Too Large:默认 1 MiB 的边界精确到 1 字节,client_max_body_size 写在哪个 location 才生效

“413 Request Entity Too Large” 的标准答案是改 client_max_body_size。这篇在本机用自己的 nginx 把默认值的边界、写在哪个位置才生效、0 的含义、分块上传的判断时机、API 的 JSON 413 以及“到底是不是 nginx 拒绝的”逐个测了一遍。

1048576 / 1048577
默认限制 1 MiB 的边界:恰好 1 MiB 通过,多 1 字节 413
0 条
上游应用自己返回 413 时 error.log 里的错误条数(nginx 自己拒绝时有 too large body 记录)
983884+65524
分块传输被拒时日志里的两个数,合计略超过 1 MiB(两个数各自的含义本篇没有查);客户端声明的 30000000 字节没有出现

默认值

实测 · 本机执行输出
  POST 1048576 字节:HTTP 200,upstream got 1048576 bytes;上游收到 1048576
  POST 1048577 字节:HTTP 413,413 Request Entity Too Large;上游收到 (没有收到请求)
      error.log: [error] *4 client intended to send too large body: 1048577 bytes, request: "POST / HTTP/1.1", host: "127.0.0.1:9780"
  POST 1500000 字节:HTTP 413,413 Request Entity Too Large;上游收到 (没有收到请求)
      error.log: [error] *5 client intended to send too large body: 1500000 bytes, request: "POST / HTTP/1.1", host: "127.0.0.1:9780"

默认 1 MiB,边界精确到 1 字节;被拒时上游收不到请求。

写在哪

实测 · 本机执行输出
  POST 5000000 字节到 /api:HTTP 200;上游收到 5000000
  POST 5000000 字节到 /upload:HTTP 413;上游收到 (没有收到请求)
  POST 20000 字节到 /tiny:HTTP 413;上游收到 (没有收到请求)

http / server / location 都可以,上传走哪个 location 就要在那里或上层写够。

0 与判断时机

实测 · 本机执行输出
  client_max_body_size 0,POST 30000000 字节:HTTP 200;上游收到 30000000
  1m 限制,POST 30000000 字节(Content-Length):HTTP 413,curl 耗时 0.000574 s;上游收到 (没有收到请求)
      error.log: [error] *4 client intended to send too large body: 30000000 bytes, request: "POST /limit1m HTTP/1.1", host: "127.0.0.1:9780"
  1m 限制,POST 30000000 字节(分块,没有 Content-Length):HTTP 413,curl 耗时 0.001413 s;curl 退出码 0;上游收到 (没有收到请求)
      error.log: [error] *5 client intended to send too large chunked body: 983884+65524 bytes, request: "POST /limit1m HTTP/1.1", host: "127.0.0.1:9780"

0 不检查;有 Content-Length 读完请求头就拒绝,分块则读到超过才拒绝。

自定义 413 响应

实测 · 本机执行输出
  POST 5000000 字节:HTTP 413,body = {"error":"payload too large","limit":"1m"}
  Python urllib 一次发 5000000 字节:HTTP 413,body = {"error":"payload too large","limit":"1m"}

error_page 413 指向一个 location,API 可返回 JSON。

是不是 nginx 拒绝的

实测 · 本机执行输出
  nginx 允许 50m,上游应用读完请求体后自己拒绝:HTTP 413,页面 "upstream app says 413",error.log 里 0 条错误

nginx 自己拒绝有 too large body 日志;上游应用的 413 被透传,日志里没有错误。

分步演示

请求体过大
本步的对象

    本文用到的工具与边界

    • 本机 macOS 27 arm64;报错文本都是真实复现时原样捕获的(命令行工具统一用 LC_ALL=C 取英文原文,路径换成 );所有服务都是本机上自己起的、只监听 127.0.0.1,不访问外网;计时用 time.perf_counter,数字每次运行会有小幅抖动。本篇用 nginx/1.31.7 与 curl 8.7.1;每个实验起一个自己的 nginx(自己的前缀目录与配置,只监听 127.0.0.1:9780),上游是 Python 脚本里起的小服务,会记录收到的字节数;请求体是重复的字节,不是真实文件
    • 没有验证:multipart 表单(浏览器上传)在 Content-Length 之外的差别;HTTP/2 下的判断时机;请求体先落临时文件(client_body_buffer_size 与 client_body_temp_path)的行为;上游在读完请求体之前就回应并关闭连接时 nginx 的表现(试过一次得到 502 Broken pipe,另一次得到透传的 413,取决于时序,没有稳定复现);云厂商网关、CDN、ingress 控制器各自的请求体上限;PHP 的 upload_max_filesize / post_max_size 等应用层限制
    京ICP备2026067502号-1京公网安备11010502063487号