Cache-Control Header

最後更新: 2022-10-27

Header

  • Cache-Control
  • Expires 與 Pragma
  • Vary header
  • ETag

 


Cache-Control

 

  • "no-cache"  表示必須先與伺服器確認傳回的回應是否已變更(透過 ETag 檢查)
  • "no-store"   禁止 Browser 和 CDN cache 它 (隱私資料)
  • "max-age"  從目前請求起 cache N 秒
  • "public"      可有可無的設定
  • "private"    內容只開放給單一使用者, 因此 CDN 不應 cache 它 (Browser 是可以 cache 的)

* 只能建議 CDN 如何去 cache, CDN 如何做就強制不了.

ie.

Apache

<FilesMatch ".(ico|js|css)$">
  Header set Cache-Control "max-age=3600, private"
</FilesMatch>

 


Expires 與 Pragma

 

Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache
Pragma: no-cache

Pragma: no-cache => "Cache-Control: no-store, no-cache"

Pragma = 舊方式 (新: cache-control: no-cache)

* "cache-control" headers take precedence on most modern systems

 


Vary response header

 

Server --> Client

In contrast to the previous Accept-* headers, which are sent by the client,

The Vary HTTP header is sent by the web server in its response.

----

Use this header if you dynamically serve different content for the same URL.

It indicates the list of headers(i.e. User-Agent) the server uses during the server-driven content negotiation phase.

The Vary header is needed to inform the cache of the decision criteria so that it can reproduce it.

----

目的: 防止 cache 錯野 (mobile 版, desktop 版)

----

 

Vary: User-Agent

It is a http header stating that different content is served to different User-Agent(Brownser)

----

Vary: *

 

The special value '*' means that the server-driven content negotiation also

uses information not conveyed in a header to choose the appropriate content.

Obviously, the wildcard '*' prevents caching from occurring, as the cache can't know what element is behind it.

----

If server can't provide a suitable resource,

it might respond with 406 (Not Acceptable) or 415 (Unsupported Media Type)

 


ETag

 

ETag 的功用是如果資源的內容沒有發生改變, Web服務器就不需要發送一個完整的響應

要點

  • ETag 的比較只對同一個URL有意義
  • ETag在HTTP頭字段中的使用是可選的
  • 沒有明確指定生成ETag值的方法 (版本號, CRC, MD5)
  • 客戶端可以決定是否緩存這個資源和它的ETag。

強/弱 ETag

  • "123456789"          # 強ETag驗證符
  • W/"123456789"     # 弱ETag驗證符

強 ETag 要求兩個資源內容的每個字節需完全相同

運作

如果客戶端再次訪問相同的URL, 將會發送一個包含已保存的ETag 的 "If-None-Match" header

客戶端請求之後, 服務器可能會比較客戶端的ETag和當前版本資源的ETag,

如果 ETag 值匹配, 那服務器便會發送回一個極短的響應(304)

myurl=https://datahunter.org/themes/mytheme/logo.png

curl -I $myurl

HTTP/1.1 200 OK
...
ETag: "639f-15fc-4a0f77094aa40"

curl -I -H 'If-None-Match: "639f-15fc-4a0f77094aa40"' $myurl

HTTP/1.1 304 Not Modified

 

Creative Commons license icon Creative Commons license icon