Cache-Control 是 HTTP/1.1 中的一個重要頭部,用於定義請求和響應的快取策略。

通過設置 Cache-Control 頭部,可以控制瀏覽器和中間代理(如 CDN)如何快取響應。

這對於提高網頁性能、減少伺服器負載有很大的幫助。

Cache-Control 指令

常用指令

  1. public
  2. private
  3. no-cache
  4. no-store
  5. max-age=<seconds>
  6. s-maxage=<seconds>
  7. must-revalidate
  8. proxy-revalidate
  9. stale-while-revalidate=<seconds>
  10. stale-if-error=<seconds>

範例

下面是一個綜合使用 Cache-Control 頭部的例子,適用於伺服器端渲染 (SSR) 的 Next.js 頁面:

export async function getServerSideProps(context) {
  // 設置 Cache-Control 頭部
  context.res.setHeader('Cache-Control', 'public, s-maxage=10, stale-while-revalidate=59');

  // 從 API 或數據庫獲取數據
  const res = await fetch('<https://api.example.com/data>');
  const data = await res.json();

  return {
    props: {
      data,
    },
  };
}

這個例子中,Cache-Control: public, s-maxage=10, stale-while-revalidate=59 的意思是: