Nginx 限制模組:ngx_http_limit_conn_module + limit_req
http 區塊定義共享記憶體區
http {
# 連線數限制區:key=客戶端IP二進制,10MB 可存約 32 萬狀態
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
# 請求頻率限制區:每秒請求數
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
}
server/location 套用限制
server {
location / {
# 連線數限制:單 IP 最大 20 條並發連線
limit_conn conn_limit 20;
limit_conn_log_level warn;
limit_conn_status 503;
# 頻寬限制:單連線 500 KB/s (對下載類業務有效)
limit_rate 500k;
limit_rate_after 1m; # 前 1MB 不限速,之後限速
# 請求頻率限制:突發 20,平滑 10r/s
limit_req zone=req_limit burst=20 nodelay;
limit_req_status 503;
}
# 靜態資源放寬限制
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
limit_conn conn_limit 50;
limit_rate 0; # 不限速
}
}
重載驗證
nginx -t && nginx -s reload
# 壓測驗證
webbench -c 100 -t 10 https://localhost/
# 檢查 503 回應
grep ' 503 ' /var/log/nginx/access.log
Apache 限制方案一:mod_limitipconn (連線數)
安裝
wget https://dominia.org/djao/limitipconn2.html
tar zxvf mod_limitipconn-0.24.tar.gz
cd mod_limitipconn-0.24
/usr/local/apache2/bin/apxs -c -i mod_limitipconn.c
配置
# httpd.conf
LoadModule limitipconn_module modules/mod_limitipconn.so
ExtendedStatus On
<IfModule mod_limitipconn.c>
<Location />
MaxConnPerIP 6
NoIPLimit image/* # 圖片不限制
</Location>
<Location /download>
MaxConnPerIP 1 # 下載目錄單連線
</Location>
</IfModule>
Apache 限制方案二:mod_bw / mod_bwlimit (頻寬+連線數)
安裝 mod_bw
wget https://bwmod.sourceforge.net/files/mod_bw-0.8.tgz
tar zxvf mod_bw-0.8.tgz
cd mod_bw
/usr/local/apache2/bin/apxs -c -i mod_bw.c
虛擬主機完整配置範例
LoadModule bw_module modules/mod_bw.so
<VirtualHost *:10004>
ServerName bw.example.com
DocumentRoot "/home/www/test"
BandWidthModule On
ForceBandWidthModule On
# 全域頻寬限制
BandWidth all 1024000 # 1 MB/s 總頻寬
MinBandWidth all 50000 # 保證最小 50 KB/s
# 大檔案限速
LargeFileLimit * 500 50000 # 超過 500KB 限速 50 KB/s
# 連線數限制
MaxConnection all 6 # 全域單 IP 最大 6 連線
MaxConnection 192.168.1.5 5 # 特定 IP 限 5
# 依 User-Agent 限速
BandWidth "u:^Mozilla" 10240
BandWidth "u:wget" 10240
# 依副檔名限速
LargeFileLimit .jpg 100 10240
# 超速錯誤頁
ErrorDocument 510 /exceed_speed.html
BandWidthError 510
ErrorLog "/var/log/apache2/bw_error.log"
CustomLog "/var/log/apache2/bw_access.log" common
</VirtualHost>
模組參數速查表
| 指令 | 範例 | 說明 |
BandWidth | BandWidth 192.168.1.5 102400 | 特定 IP 限速 100KB/s |
BandWidth | BandWidth "u:wget" 10240 | wget 下載限速 10KB/s |
MinBandWidth | MinBandWidth all -1 | 保證最小速度 |
LargeFileLimit | LargeFileLimit .jpg 100 10240 | jpg>100KB 限速 10KB/s |
MaxConnection | MaxConnection all 10 | 單 IP 最大連線數 |
BandWidthError | BandWidthError 510 | 超速返回 510 狀態碼 |
選型建議
| 需求 | 推薦方案 |
| 純連線數限制、配置簡單 | Nginx limit_conn / Apache mod_limitipconn |
| 頻寬限制、大檔案分級限速 | Nginx limit_rate / Apache mod_bw |
| 請求頻率限制 (API 防刷) | Nginx limit_req (效能最佳) |
| 依 User-Agent/Referer 精細控制 | Apache mod_bw (正則支援豐富) |
| 高併發、記憶體效率 | Nginx (原生模組、無額外進程) |
避坑提醒
- 限制發生在 **應用層**,無法防禦 SYN Flood 等傳輸層攻擊,需配合防火牆/反向代理
- CDN/負載均衡後端,真實 IP 需透過
X-Forwarded-For 取得,Nginx 用 $http_x_forwarded_for 或 realip_module
- 過度限制導致正常用戶 (企業出口 NAT) 誤傷,建議設定白名單機制
- 壓測驗證時觀察錯誤日誌,確認 503/510 狀態碼正確返回