萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Squid 強制緩存動態頁面實戰:忽略 Cache-Control: no-cache 的關鍵參數

Squid 預設遵循 HTTP 協議,遇到 Cache-Control: no-cache、Pragma: no-cache 或 Expires: 0 的響應會拒絕緩存。但對於 API 響應、地圖瓦片、動態生成但短期不變的頁面,強制緩存能大幅降低上游壓力、提升響應速度。本文記錄踩坑過程與關鍵參數 ignore-no-cache、ignore-private 的正確用法。

場景:緩存 Yupoo API 請求

  • 請求 URL:www.yupoo.com/api/rest/?method=xxx&...
  • 響應頭:Cache-Control: no-cache, must-revalidate / Pragma: no-cache
  • 目標:在 Squid 層面緩存 24 小時,減少跨域代理延遲

失敗嘗試:標準 refresh_pattern 無效

acl QUERY urlpath_regex cgi-bin \?
acl forcecache url_regex -i yupoo.com
no_cache allow forcecache
no_cache deny QUERY

refresh_pattern -i yupoo.com 1440 50% 10080 override-expire override-lastmod reload-into-ims ignore-reload

結果:access.log 全是 TCP_MISS,完全未命中緩存。

根因分析

Squid 內核在 store.cc 中檢查響應頭:

  • 若存在 Cache-Control: no-cache 或 Pragma: no-cache,直接標記為不可緩存
  • override-expire、override-lastmod、reload-into-ims、ignore-reload 只能覆蓋 Expires/Last-Modified,無法覆蓋 no-cache 指令

解決方案:擴展參數 ignore-no-cache / ignore-private

這兩個參數是 Squid 2.6+ 透過補丁引入,文檔鮮有記載,但源碼確認有效:

refresh_pattern -i yupoo.com 1440 50% 10080 \
    override-expire override-lastmod reload-into-ims \
    ignore-reload ignore-no-cache ignore-private

參數含義

參數作用
ignore-no-cache忽略響應頭 Cache-Control: no-cache 與 Pragma: no-cache
ignore-private忽略 Cache-Control: private(原本僅允許客戶端緩存,不允許代理緩存)
override-expire忽略 Expires 頭,強制使用 min/max 時間
override-lastmod忽略 Last-Modified,強制使用啟發式過期算法
reload-into-ims客戶端無條件重載時轉為 If-Modified-Since 請求
ignore-reload忽略客戶端 Cache-Control: no-cache 請求頭(客戶端強制刷新)

驗證生效

squid -k reconfigure
tail -f /var/log/squid/access.log
# 出現 TCP_HIT/200、TCP_MEM_HIT/200 即成功

補充:Google Earth / Maps 正確配置

原文配置有誤(域名寫錯、缺少 ignore-no-cache),修正版:

acl QUERY urlpath_regex cgi-bin \? intranet
acl forcecache url_regex -i kh\.google\.com mt\.google\.com mapgoogle\.mapabc\.com keyhole\.com
no_cache allow forcecache
no_cache deny QUERY

refresh_pattern -i kh\.google\.com 1440 20% 10080 override-expire override-lastmod reload-into-ims ignore-reload ignore-no-cache ignore-private
refresh_pattern -i mt\.google\.com 1440 20% 10080 override-expire override-lastmod reload-into-ims ignore-reload ignore-no-cache ignore-private
refresh_pattern -i mapgoogle\.mapabc\.com 1440 20% 10080 override-expire override-lastmod reload-into-ims ignore-reload ignore-no-cache ignore-private
refresh_pattern -i keyhole\.com 1440 20% 10080 override-expire override-lastmod reload-into-ims ignore-reload ignore-no-cache ignore-private

避坑提醒

  • 濫用風險:強制緩存可能導致用戶看到過期數據,僅用於可容忍短期不一致的場景(地圖瓦片、公開 API、靜態資源)
  • 定期清理:配合 squid -k rotate 或 cron 清理 cache_dir
  • 監控指標:關注 cache_hit_ratio、swap.out、disk_usage
copyright © 萬盛學電腦網 all rights reserved