在 Nginx 中限制带宽可以有效防止资源滥用,确保公平分配网络资源。以下是 6 种精准控制带宽的方法,涵盖静态文件、动态内容、全局限速等场景:
1. 全局限速(HTTP 层)
限制所有连接的传输速率:
http {
limit_rate_after 1m; # 前1MB不限速(加速首屏加载)
limit_rate 100k; # 后续速率限制为100KB/s
}
适用场景:全站统一限速,适合小型服务器。
2. 按连接限速(Location 层)
针对特定路径(如下载目录)限速:
location /download/ {
limit_rate 50k; # 每个连接限速50KB/s
limit_rate_after 500k; # 前500KB不限速
}
测试效果:
wget http://example.com/download/largefile.zip
3. 动态内容代理限速
限制反向代理到后端的传输速率:
location /video/ {
proxy_pass http://backend;
proxy_limit_rate 200k; # 从后端读取时限速200KB/s
}
4. 基于 IP 的差异化限速
结合 geo
和 map
实现不同 IP 段不同速率:
geo $limit_ip {
default 0;
192.168.1.0/24 1; # 内网不限速
10.0.0.1 2; # 特定IP更高速率
}
map $limit_ip $limit_rate {
0 50k; # 默认50KB/s
1 off; # 内网不限速
2 200k; # 特权IP 200KB/s
}
server {
location / {
limit_rate $limit_rate;
}
}
5. 突发带宽控制(Nginx Plus 或第三方模块)
允许短时间突发流量,然后限速:
location /burst/ {
burst 10m; # 允许突发10MB
limit_rate 1m; # 突发后限速1MB/s
}
开源替代方案:
使用 ngx_http_limit_req_module
限制请求速率间接控制带宽。
6. 高级限速(Lua + Redis)
通过 OpenResty 动态调整限速策略:
location /dynamic/ {
access_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
red:connect("127.0.0.1", 6379)
local rate = red:get("user_rate:" .. ngx.var.remote_addr)
ngx.var.limit_rate = rate or "100k" # 默认100KB/s
}
}
适用场景:需要根据用户等级实时调整速率。
完整配置示例(综合限速)
http {
# 全局默认限速
limit_rate_after 1m;
limit_rate 100k;
server {
listen 80;
server_name example.com;
# 静态资源目录严格限速
location /assets/ {
limit_rate 50k;
limit_rate_after 0; # 立即限速
}
# 视频流媒体动态限速
location /videos/ {
proxy_pass http://media_server;
proxy_limit_rate 500k; # 后端到Nginx的速率
limit_rate 300k; # 客户端到Nginx的速率
}
# API接口按IP限速
location /api/ {
limit_req zone=api_limit burst=5;
limit_rate $binary_remote_addr 100k; # 每个IP 100KB/s
}
}
# 限流区定义(配合limit_req)
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
}
验证方法
- 实时监控带宽:
iftop -i eth0 # 查看实时流量 nload eth0 # 分IP统计带宽
- 测试下载速度:
wget -O /dev/null http://example.com/largefile 2>&1 | grep -o '[0-9.]+ [KM]*B/s'
- 日志记录:
log_format bandwidth '$remote_addr - $bytes_sent - $request_time'; access_log /var/log/nginx/bandwidth.log bandwidth;
性能调优建议
- 连接数平衡:
结合limit_conn
防止单个IP占用所有带宽:limit_conn_zone $binary_remote_addr zone=conn_zone:10m; limit_conn conn_zone 5; # 每个IP最多5个连接
- TCP 优化:
调整内核参数提升限速稳定性:echo "net.ipv4.tcp_window_scaling = 1" >> /etc/sysctl.conf sysctl -p
- 硬件加速:
对于高流量场景,启用网卡多队列:ethtool -L eth0 combined 8
常见问题
- 限速不生效
- 检查是否被上层 CDN 或代理缓存。
- 确认
limit_rate
不在if
块内(Nginx 限制)。
- 速度波动大
- 增加
limit_rate_after
缓冲值。 - 检查网络拥塞(
ping
和traceroute
)。
- 增加
- 高并发下失效
- 结合
limit_conn
控制并发连接数。
- 结合
通过以上方法,可以精细控制 Nginx 的带宽分配,既能防止资源耗尽,又能保障关键服务的流畅性。生产环境中建议结合监控工具(如 Grafana + Prometheus)实时观察限速效果。
- - - - - - - 剩余部分未读 - - - - - - -
扫描关注微信公众号获取验证码,阅读全文
你也可以查看我的公众号文章,阅读全文
你还可以登录,阅读全文
原文出处:
内容由AI生成仅供参考,请勿使用于商业用途。如若转载请注明原文及出处。
出处地址:http://www.07sucai.com/tech/978.html
版权声明:本文来源地址若非本站均为转载,若侵害到您的权利,请及时联系我们,我们会在第一时间进行处理。