Nginx反向代理SSE大文件上传异常问题求助
解决Nginx代理SSE文件上传时大文件截断问题
问题描述
我们为文件上传API端点实现了SSE(Server-Sent-Event),该POST /media接口接收multipart/form-data格式的文件,接口响应为Content-Type: text/event-stream的事件流。
示例curl请求:
curl --location --request POST 'https://localhost/api/v1/media' --form 'file=@"/home/shivam/Downloads/with_no_cover_image.mp3"'
不使用Nginx时,任意大小的文件均可正常上传并获取正确的事件流响应;但通过Nginx代理请求时,仅能上传约2.5MB以下的文件,超过该大小的文件无法完整上传至服务器,调试发现服务器仅收到2.5MB数据。
当前Nginx配置如下:
user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; } http { sendfile on; tcp_nopush on; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; server { listen 443 ssl; server_name localhost; client_max_body_size 500M; root /home/manoj/instaglitch/build; ssl on; ssl_protocols TLSv1.2 TLSv1.3; proxy_set_header Cookie ""; ssl_certificate certificate.crt; ssl_certificate_key private.key; location / { proxy_read_timeout 1h; proxy_connect_timeout 1h; proxy_send_timeout 1h; proxy_set_header Connection ''; proxy_http_version 1.1; chunked_transfer_encoding off; proxy_pass https://localhost:8080; proxy_set_header HOST $http_host; proxy_set_header Cookie ""; } } }
解决方案
1. 关闭代理请求体缓冲(优先推荐)
在location /块中添加proxy_request_buffering off;,禁用Nginx对客户端请求体的缓冲功能,让Nginx实时将请求数据转发到后端服务器,适配SSE的流式传输场景:
location / { proxy_read_timeout 1h; proxy_connect_timeout 1h; proxy_send_timeout 1h; proxy_set_header Connection ''; proxy_http_version 1.1; chunked_transfer_encoding off; # 添加以下配置关闭请求体缓冲 proxy_request_buffering off; proxy_pass https://localhost:8080; proxy_set_header HOST $http_host; proxy_set_header Cookie ""; }
2. 调整客户端请求体缓冲大小(备选方案)
如果不想完全关闭缓冲,可以增大client_body_buffer_size,让Nginx在内存中缓冲更大的请求体,避免因缓冲不足导致截断。在http块或server块中添加:
client_body_buffer_size 100M;
同时确保client_body_temp_path指定的临时目录存在且Nginx进程(www-data用户)有读写权限,默认路径为/usr/share/nginx/client_body_temp,若不存在可手动创建并授权:
mkdir -p /usr/share/nginx/client_body_temp chown www-data:www-data /usr/share/nginx/client_body_temp chmod 700 /usr/share/nginx/client_body_temp
3. 验证配置并重启Nginx
修改配置后,检查配置语法是否正确:
nginx -t
确认无错误后,重启Nginx生效:
systemctl restart nginx
内容的提问来源于stack exchange,提问作者Shivam gupta
相关产品推荐
相关产品推荐

