nginx 413问题解决

问题

client_max_body_size 这个参数,本质上是 限制 HTTP 请求体(body)最大大小。超过这个大小,Nginx 直接返回 413 Request Entity Too Large

很多人以为它只影响上传文件,其实它控制的是整个请求体大小——包括 JSON、表单、文件上传等。


解决

Nginx 是“块级继承模型”,也就是:就近原则覆盖

client_max_body_size可以配置在:

  • http {} —— 全局生效
  • server {} —— 针对某个虚拟主机
  • location {} —— 针对某个接口路径

优先级:

location > server > http

举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
http {
client_max_body_size 50M;

server {
listen 80;
server_name example.com;

client_max_body_size 100M;

location /upload {
client_max_body_size 500M;
}
}
}

含义是:

  • 默认最大 50M
  • example.com 是 100M
  • /upload 允许 500M

client_max_body_size默认值是多少?

默认是 1M。(nginx对大小写不敏感 1M = 1m)
是的,非常小,如果你什么都不配,上传 2M 文件就会 413。

### 检查配置是否生效
nginx -T | grep client_max_body_size