Nginx 修改上传文件大小限制
一、修改上传文件大小限制
使用 nginx 前端服务器,应用一切正常,但是管理后台上传超过 1M 文件时无法正常上传,提示上传文件太大(Http 413 错误,413 Request Entity Too Large),于是修改了下 nginx 配置中的 client_max_body_size 这个参数,Nginx 上传文件大小默认是 1M ,需要设置为合理的值。官方解释如下:
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.
这里项目中配置如下:
location / {
proxy_pass http://www.xxx.com/service;
proxy_redirect off;
proxy_set_header Host $host:80;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 1024m;
}
测试一下配置文件
# nginx -t
# nginx -s reload
这里设置为 1G 的上限,通过修改 client_max_body_size 的大小,解决了文件上传问题。
注意:需要注意 client_max_body_size 放置的位置,否则可能不会生效。
二、与 client_body_buffer_size 配合使用
Nginx 分配给请求数据的Buffer大小,如果请求的数据小于 client_body_buffer_size 直接将数据先在内存中存储。如果请求的值大于client_body_buffer_size 小于 client_max_body_size,就会将数据先存储到临时文件中(client_body_temp 指定的路径中),默认该路径值是 /tmp/。
需要注意的是,配置的 client_body_temp 地址要让执行的 Nginx 的用户组有读写权限。否则,当传输的数据大于 client_body_buffer_size,写进临时文件失败会没有权限的错。如下:
20648 open() "/usr/local/openresty-1.9.7.5/nginx/client_body_temp/0000000019" failed (13: Permission denied)
三、总结
传输的数据大于client_max_body_size,一定是传不成功的。小于client_body_buffer_size直接在内存中高效存储。如果大于client_body_buffer_size小于client_max_body_size会存储临时文件,临时文件一定要有权限。
如果追求效率,就设置 client_max_body_size、client_body_buffer_size相同的值,这样就不会存储临时文件,直接存储在内存了。