Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

IIS 設置 HTTP 緩存過期時間 (Cache-Control/Expires) 圖文教程

編輯:關於伺服器

正確配置靜態資源緩存過期時間,能顯著減少回源請求、降低帶寬成本、提升頁面加載速度。IIS 提供 GUI 方式設置站點級/目錄級/文件級 `Cache-Control: max-age` 與 `Expires` 頭。

操作步驟 (IIS 7.0 - 10.0 通用)

  1. 打開「Internet Information Services (IIS) 管理器」。
  2. 左側連線面板選中目標 **網站** (或展開網站選中特定 **目錄/文件** 實現差異化策略)。
  3. 中間功能視圖雙擊 HTTP 回應標頭。
  4. 右側動作欄點擊 「設置通用標頭...」** (或直接在列表中編輯現有 `Cache-Control`/`Expires`)。
  5. 在彈出對話框中:
  • 勾選 「啟用內容過期」**。
  • 選擇 「過期後」** → 輸入數值與單位:
資源類型建議過期時間單位選擇生成頭示例
靜態資源 (JS/CSS/圖片/字體/視頻) - 含版本戳/哈希文件名365 天 (1 年)天Cache-Control: max-age=31536000
靜態資源 - 無版本控制30 天天Cache-Control: max-age=2592000
半動態頁面 (個性化推薦片段)5-10 分鐘分鐘Cache-Control: max-age=300
API 回應 (允許緩存)1-5 分鐘分鐘/秒Cache-Control: max-age=60
不應緩存 (登入頁/支付/即時數據)立即過期選「立即過期」Cache-Control: no-cache, no-store, must-revalidate
  1. 點擊「確定」應用。IIS 即時生效,無需重啟服務。

進階:自定義 Cache-Control 指令

GUI 僅支援 `max-age`/`Expires`。若需添加 `public`/`private`/`must-revalidate`/`stale-while-revalidate` 等指令,需在 `web.config` 中配置:

<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" cacheControlCustom="public, must-revalidate" />
    </staticContent>
    <httpProtocol>
      <customHeaders>
        <add name="Cache-Control" value="public, max-age=31536000, stale-while-revalidate=86400" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

驗證方法

  • 瀏覽器開發者工具 Network 面板 → 選中靜態資源 → Headers → 查看 `Cache-Control`、`Expires`、`Age` (CDN 節點緩存秒數)。
  • 命令行:curl -I https://example.com/static/app.js 檢查響應頭。

常見誤區

  • ❌ 以為設置後「立即生效所有用戶」:瀏覽器/CDN 已緩存舊版本需等待過期或手動清理/強制刷新 (Ctrl+F5)。
  • ❌ 所有資源統一設置長過期:無版本控制的 CSS/JS 更新後用戶獲取舊文件導致頁面錯亂,**必須配合文件名哈希/版本號部署策略**。
  • ❌ 忽略 `Vary: Accept-Encoding`:啟用 GZIP/Brotli 時,IIS 自動添加,確保 CDN/代理正確區分壓縮/未壓縮版本。
Copyright © Windows教程網 All Rights Reserved