Cache-Control 是 HTTP/1.1 中的一個重要頭部,用於定義請求和響應的快取策略。
通過設置 Cache-Control 頭部,可以控制瀏覽器和中間代理(如 CDN)如何快取響應。
這對於提高網頁性能、減少伺服器負載有很大的幫助。
Cache-Control 指令public
Cache-Control: publicprivate
Cache-Control: privateno-cache
Cache-Control: no-cacheno-store
Cache-Control: no-storemax-age=<seconds>
Cache-Control: max-age=3600(快取 1 小時)s-maxage=<seconds>
max-age 類似,但僅適用於共享快取(如 CDN),而不是瀏覽器。Cache-Control: s-maxage=3600must-revalidate
Cache-Control: must-revalidateproxy-revalidate
must-revalidate 類似,但僅適用於中間代理快取。Cache-Control: proxy-revalidatestale-while-revalidate=<seconds>
Cache-Control: stale-while-revalidate=60stale-if-error=<seconds>
Cache-Control: stale-if-error=86400(1 天)下面是一個綜合使用 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 的意思是: