server {listen 80;server_name your.domain.com; # 替換為你的域名root /usr/share/nginx/html; # 替換為你的項目根目錄# 規則1:HTML 文件 - 永不緩存# 這是最關鍵的一步,確保瀏覽器總是獲取最新的入口文件。location = /index.html {add_header Cache-Control "no-cache, no-store, must-revalidate";add_header Pragma "no-cache";add_header Expires "0";}# 規則2:帶 Hash 的靜態資源 - 永久緩存# 文件名中的 Hash 確保了內容變化時文件名也會變化,所以可以放心地讓瀏覽器永久緩存。# `immutable` 告訴瀏覽器這個文件內容永遠不會變,連校驗請求都無需發送。location ~* \.[a-f0-9]{8}\.(css|js)$ {expires 1y;add_header Cache-Control "public, immutable";}# 規則3:其他靜態資源(如圖片、字體) - 長期緩存# 這些文件通常不帶 Hash,但也不常變動,可以設置一個較長的緩存時間。location ~* \.(jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf)$ {expires 30d;add_header Cache-Control "public";}# 規則4:單頁應用(SPA)路由處理# 這是保證 React/Vue 等路由正常工作的關鍵。# 重要的是,它會將所有未匹配到具體文件的請求都交由 index.html 處理。# 由于我們已為 /index.html 單獨設置了不緩存規則,所以這里是安全的。location / {try_files $uri $uri/ /index.html;}
}