| 指令 | 作用域 | 說明 |
| limit_zone | http | 定義共享記憶體區儲存會話狀態 (舊版語法,Nginx 1.1.8+ 建議用 limit_conn_zone) |
| limit_conn_zone | http | limit_conn_zone $binary_remote_addr zone=one:10m; 定義 10MB 區域名 one |
| limit_conn | http/server/location | limit_conn one 2; 限制同一鍵值 (IP) 並發連線數 |
| limit_rate | http/server/location | limit_rate 40k; 限制**單連線**傳輸速度 (位元組/秒) |
基礎配置範例 (全站限速)
http {
limit_conn_zone $binary_remote_addr zone=one:10m;
server {
location / {
limit_conn one 2; # 每 IP 最多 2 條並發連線
limit_rate 40k; # 每連線 40 KB/s
# 實際單 IP 總頻寬上限 ≈ 80 KB/s
}
}
}
進階場景案例
案例 1:下載目錄單連線 100KB/s,僅允許 1 條連線
location /download/ {
limit_conn one 1;
limit_rate 100k;
}
案例 2:全站總速 100KB/s,允許 5 條連線 (單連線 20KB/s)
location / {
limit_conn one 5;
limit_rate 20k;
# 5 × 20k = 100k 總上限
}
關鍵原理解析
$binary_remote_addr:客戶端 IP 二進制形式,佔用 4/16 位元組,**比字串 IP 節省 50%+ 記憶體**,適合高併發。
limit_zone/limit_conn_zone 大小規劃:10MB 區約可容納 **16 萬 IP 會話狀態** (每狀態 ~64 bytes),視峰值併發調整。
limit_rate 作用於 **發送響應體階段**,不影響建立連線、SSL 握手、回應標頭傳輸。
- 需搭配
limit_conn 否則單 IP 開啟大量連線可繞過單連線限速。
驗證測試
# 模擬 3 條並發下載 (超過 limit_conn 2)
for i in {1..3}; do curl --limit-rate 500k -o /dev/null https://example.com/largefile & done
# 第 3 條應回 503 (Service Unavailable) 或排隊
# 驗證單連線速度
curl --limit-rate 1m -o /dev/null https://example.com/largefile
# 實際速度應被限制在 40KB/s 左右
生產環境建議
- 靜態資源 (圖片、視頻) 配置獨立
location 限速,避免影響 API/頁面載入。
- 結合
limit_req_zone (請求頻率限制) 防 CC 攻擊:
limit_req_zone $binary_remote_addr zone=req:10m rate=10r/s;
- 監控
ngx_http_limit_conn_module 共享記憶體使用率,防區域耗盡導致全站 503。