在 Debian 上用 Nginx 限速,通常是通过 limit_req(限制请求频率)和 limit_rate(限制带宽)来实现。下面按常见场景说明。
sudo apt update
sudo apt install nginx
http 块定义限速区编辑:
sudo nano /etc/nginx/nginx.conf
在 http {} 内添加:
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
含义:
$binary_remote_addr:按客户端 IP 限速10m:共享内存大小rate=10r/s:每秒最多 10 个请求server 或 location 中使用server {
listen 80;
server_name example.com;
location /api/ {
limit_req zone=req_limit burst=20 nodelay;
proxy_pass http://backend;
}
}
参数说明:
burst=20:允许突发 20 个请求nodelay:突发请求立即处理(否则排队)limit_rate 100k;
表示每个连接最大 100KB/s
location /download/ {
limit_rate 200k;
}
location /video/ {
limit_rate_after 1m;
limit_rate 500k;
}
含义:
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
location / {
limit_conn conn_limit 5;
}
}
表示每个 IP 最多 5 个并发连接
sudo nginx -t
sudo systemctl reload nginx
http {
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=5r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
}
server {
location /api/ {
limit_req zone=api_limit burst=10 nodelay;
limit_conn conn_limit 10;
}
location /files/ {
limit_rate 300k;
}
}
如果你有 具体场景(比如:
可以告诉我,我给你定制配置。