温馨提示×

debian nginx怎么限速

小樊
38
2026-09-24 20:29:29
栏目: 智能运维

在 Debian 上用 Nginx 限速,通常是通过 limit_req(限制请求频率)和 limit_rate(限制带宽)来实现。下面按常见场景说明。


一、安装 Nginx(如已安装可跳过)

sudo apt update
sudo apt install nginx

二、限制请求频率(防刷接口)

1️⃣ 在 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 个请求

2️⃣ 在 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:突发请求立即处理(否则排队)

三、限制下载速度(带宽限速)

1️⃣ 全局限速(http 或 server)

limit_rate 100k;

表示每个连接最大 100KB/s


2️⃣ 只对下载文件限速

location /download/ {
    limit_rate 200k;
}

3️⃣ 按条件动态限速(可选)

location /video/ {
    limit_rate_after 1m;
    limit_rate 500k;
}

含义:

  • 前 1MB 不限制
  • 超过后限速 500KB/s

四、限制连接数(防止过多连接)

limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

server {
    location / {
        limit_conn conn_limit 5;
    }
}

表示每个 IP 最多 5 个并发连接


五、检查并重载 Nginx

sudo nginx -t
sudo systemctl reload nginx

六、常见组合示例(API + 下载)

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;
    }
}

如果你有 具体场景(比如:

  • 只限速某个 IP
  • 限速 WordPress
  • 限制爬虫
  • 限制 HTTPS

可以告诉我,我给你定制配置。

0 踩