萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Nginx 設定靜態資源快取過期時間:JS、CSS、圖片最佳化

核心指令 expires

在 location 區塊中設定 expires,Nginx 會在回應標頭加入 Expires 與 Cache-Control,指示瀏覽器快取。

基本語法


location ~* \.(jpg|jpeg|png|gif|ico|webp)$ {
    expires 30d;          # 圖片快取 30 天
    add_header Cache-Control "public";
}

location ~* \.(css|js)$ {
    expires 1h;           # JS/CSS 快取 1 小時
    add_header Cache-Control "public";
}

location ~* \.(woff2?|ttf|eot)$ {
    expires 365d;         # 字型檔長期快取
    add_header Cache-Control "public";
}

參數值說明

完整 nginx.conf 片段


http {
    # 關閉版本號顯示
    server_tokens off;

    # 啟用 sendfile 零拷貝
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    # Gzip 壓縮
    gzip on;
    gzip_vary on;
    gzip_min_length 1k;
    gzip_comp_level 4;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    # 快取開啟檔案描述符
    open_file_cache max=100000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # 虛擬主機設定
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

驗證快取生效

  1. 瀏覽器開發者工具 → Network → 查看 Cache-Control、Expires 標頭
  2. 線上工具:WebKaka 網站速度診斷
  3. curl -I https://example.com/style.css 檢查回應標頭

版本控管策略

靜態檔案命名加入雜湊(如 app.a1b2c3.js),設定 expires max;HTML 頁面設定 expires -1 或 no-cache,確保使用者永遠拿到最新入口點。

總結

合理設定 expires 可大幅降低頻寬、提升首屏載入速度。搭配 Gzip、HTTP/2、CDN 可獲得最佳效能。

copyright © 萬盛學電腦網 all rights reserved
值意義
30d30 天
1h1 小時
maxExpires: 2037-12-31,Cache-Control: max-age=315360000(10 年)
epochExpires: 1970-01-01 00:00:01 GMT(永不快取)
off關閉快取標頭(預設)
-1Expires = 當下時間(強制不快取)