问题描述
在使用 Azure App Service(Linux + PHP) 部署 Web 应用时,如果上传文件大于1MB,就会遇到 HTTP 413(Request Entity Too Large) 错误。
错误截图
问题解答
一、HTTP 413 错误的本质含义
413 Request Entity Too Large 是标准 HTTP 状态码,表示:
客户端提交的请求体(Request Body)大小超过了服务器当前允许的最大限制。
在 Azure App Service(Linux)环境中,这个错误并不一定来自前端网关(Frontend),而更常见的来源是 App Service 容器内部的 Web Server(如 Nginx)或运行时(如 PHP)。
二、Nginx 默认的 client_max_body_size 限制
在 Linux App Service 中,平台内置 Nginx 作为 Web Server。
Nginx 会在请求到达应用之前,对请求体大小进行校验。
- 当上传文件大小超过 Nginx 允许的最大值时(Nginx 对上传请求体大小的默认限制为 1 MB,需要通过 client_max_body_size 参数修改大小)
- Nginx 会直接返回 413, 请求不会进入 PHP
如果未显式配置,该值通常较小,不适合文件上传场景。通过自定义 Nginx 配置,将其调整为更大的值(例如 20MB),即可解除这一层限制。
解决方案
修改 App Service默认Nginx的client_max_body_size参数
第一步:把App Service默认的Nginx配置复制到home/site/wwwroot目录中
进入kudu,选择SSH到Application, 执行cp命令cp /etc/nginx/sites-available/default /home/site/wwwroot/default
操作截图:
第二步:添加client_max_body_size参数并设置为20M
在Kudu页面的File Manager中,进入home/site/wwwroot目录中,选择default文件,直接UI上添加(client_max_body_size 20M;)后保存。
操作截图:
第三步:覆盖nginx default配置并重启
因修改了默认的nginx配置,为了使得配置生效,需要用新的配置文件覆盖默认配置,并重启nginx服务。使用如下命令:
cp /home/site/wwwroot/default /etc/nginx/sites-available/default && service nginx reload
此命令将默认 NGINX 配置文件替换为存储库根目录中命名 default 的文件,并重新启动 NGINX。
操作截图
结论
完成以上三步之后,刷新php应用的上传页面,再次上传小于20MB的文件,成功。
参考资料
Azure App Service(Linux)自定义 Nginx 配置
https://learn.microsoft.com/azure/app-service/configure-language-php?pivots=platform-linux#change-the-site-root
Nginx 官方文档:client_max_body_size
https://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size
Syntax: client_max_body_size size;
Default: client_max_body_size 1m;
Context: http, server, location
Sets the maximum allowed size of the client request body. If the size in a request exceeds the configured value, the 413 (Request Entity Too Large) error is returned to the client. Please be aware that browsers cannot correctly display this error. Setting size to 0 disables checking of client request body size.