Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Ubuntu Apache 2.4 配置 mod_ratelimit 限速功能:目錄級頻寬控制腳本化

編輯:Linux 系統常見問題解答

mod_ratelimit 簡介

Apache 2.4 內建 mod_ratelimit,透過輸出過濾器限制回應傳輸速率,適用於大檔案下載、API 節流、測試弱網環境。

一鍵部署腳本

#!/bin/bash
# rate-limit-setup.sh
# 用法: sudo bash rate-limit-setup.sh

set -e

# 1. 建立模組配置
cat > /tmp/ratelimit.conf <<'EOF'
<Directory /home/hursing/mylimiteddir/>
    SetOutputFilter RATE_LIMIT
    SetEnv rate-limit 30
</Directory>
EOF

# 2. 部署至模組目錄
cp /tmp/ratelimit.conf /etc/apache2/mods-available/

# 3. 啟用模組 (建立軟連結)
cd /etc/apache2/mods-enabled
ln -sf ../mods-available/ratelimit.load .
ln -sf ../mods-available/ratelimit.conf .

# 4. 重啟生效
systemctl restart apache2

echo "Rate limit 30 KB/s applied to /home/hursing/mylimiteddir/"

配置詳解

指令說明
SetOutputFilter RATE_LIMIT啟用限速輸出過濾器
SetEnv rate-limit 30限制速率 **30 KB/秒** (單位固定為 KB,整數)
<Directory ...>針對特定目錄生效

進階應用場景

1. 針對特定 URL (Location)

<Location /downloads/largefiles/>
    SetOutputFilter RATE_LIMIT
    SetEnv rate-limit 100
</Location>

2. 多目錄差異限速

<Directory /var/www/public/>
    SetOutputFilter RATE_LIMIT
    SetEnv rate-limit 50
</Directory>

<Directory /var/www/premium/>
    SetOutputFilter RATE_LIMIT
    SetEnv rate-limit 500
</Directory>

3. 全域限速 (不建議生產環境)

# 直接在 apache2.conf 或虛擬主機內 (無 Directory 包裹)
SetOutputFilter RATE_LIMIT
SetEnv rate-limit 200

4. 條件式限速 (配合 mod_setenvif)

# 僅限制特定 User-Agent
BrowserMatch "wget" limit_agent
SetEnvIf limit_agent RATE_LIMIT=10
SetOutputFilter RATE_LIMIT

驗證測試

# 1. 建立測試檔
dd if=/dev/zero of=/home/hursing/mylimiteddir/test_100mb bs=1M count=100

# 2. 下載測試 (觀察速度)
wget https://localhost/mylimiteddir/test_100mb
curl -o /dev/null https://localhost/mylimiteddir/test_100mb -w "Speed: %{speed_download} bytes/sec\n"

# 3. 預期約 30 KB/s (30000 bytes/sec)

注意事項

  • 僅限輸出:不影響上傳 (POST/PUT)
  • 整數 KB:rate-limit 不支援小數 (如 1.5 MB 需換算 1500 KB)
  • 記憶體緩衝:大檔案會佔用記憶體緩衝,高併發注意 MaxRequestWorkers 與記憶體關係
  • 模組載入順序:確保 ratelimit.load 在 filter.load 之後 (通常預設正確)
  • 不支援 .htaccess:需在主配置/虛擬主機/模組配置中設定

替代方案

方案優點缺點
mod_bw支援輸入/輸出、連線數、動態規則第三方模組,需編譯安裝
Nginx limit_rate效能更高、配置靈活、原生支援需前端置換 Nginx
tc (Traffic Control)核心層級、全協議、精確配置複雜、需 root
應用層程式控制邏輯最靈活 (用戶級、時間段、配額)開發成本高
Copyright © Windows教程網 All Rights Reserved