我使用Nginx作为反向代理
如何限制Nginx的上传速度?
我想分享一下如何限制Nginx中反向代理的上传速度
限制下载速度很容易,但上传却不容易
以下是限制上传速度的配置
- 查找您的目录
/etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 1;
}
# 1)
# Add a stream
# This stream is used to limit upload speed
stream {
upstream site {
server your.upload-api.domain1:8080;
server your.upload-api.domain1:8080;
}
server {
listen 12345;
# 19 MiB/min = ~332k/s
proxy_upload_rate 332k;
proxy_pass site;
# you can use directly without upstream
# your.upload-api.domain1:8080;
}
}
http {
server {
# 2)
# Proxy to the stream that limits upload speed
location = /upload {
# It will proxy the data immediately if off
proxy_request_buffering off;
# It will pass to the stream
# Then the stream passes to your.api.domain1:8080/upload?$args
proxy_pass http://127.0.0.1:12345/upload?$args;
}
# You see? limit the download speed is easy, no stream
location /download {
keepalive_timeout 28800s;
proxy_read_timeout 28800s;
proxy_buffering off;
# 75MiB/min = ~1300kilobytes/s
proxy_limit_rate 1300k;
proxy_pass your.api.domain1:8080;
}
}
}
如果您的Nginx不支持stream
您可能需要添加一个模块
静态:
$ ./configure --with-stream
$ make && sudo make install
动态
$ ./configure --with-stream=dynamic
- https://www.nginx.com/blog/compiling-dynamic-modules-nginx-plus/
注意:如果您有一个客户端,如HAProxy和Nginx作为服务器
在上传大文件时,您可能会在HAProxy中遇到504 timeout
,在Nginx中面临499 client is close
,但上传速度较低
您应该在HAProxy中增加或添加timeout server: 605s
或以上,因为我们希望HAProxy在Nginx忙于上传到您的服务器时不要关闭连接。https://stackoverflow.com/a/44028228/10258377
一些参考文献:
- https://nginx.org/en/docs/stream/ngx_stream_proxy_module.html#proxy_upload_rate
- http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_limit_rate
你会发现一些其他方法,通过添加第三方模块来限制上传速度,但它很复杂,不能很好地工作
- https://www.nginx.com/resources/wiki/modules/
- https://www.nginx.com/resources/wiki/modules/upload/
- https://github.com/cfsego/limit_upload_rate
稍后感谢我;(