YEGUO

Nginx静态资源缓存

|
|
2 min read

配置缓存的关键头字段

  1. Cache-Control
    • 指定资源在浏览器中的缓存策略。
    • 常见值:
      • max-age=<seconds>:设置资源的缓存时间(秒)。
      • no-cache:要求浏览器重新验证缓存资源的有效性。
      • public:资源可以被浏览器和中间代理缓存。
      • private:资源仅浏览器缓存。
  2. Expires
    • 定义资源的过期时间,通常与 Cache-Control 配合使用。

为静态资源设置缓存

location /static {
    root /usr/share/nginx;
    index index.html index.htm;

    # 添加缓存头
    expires 30d;                 # 30天后过期
    add_header Cache-Control "public";

    # 优化文件访问
    try_files $uri $uri.jpg $uri.png $uri.gif =404;
}

为不同资源设置不同的缓存时间

location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|eot|svg|webp)$ {
    expires 30d;                 # 图片和字体缓存30天
    add_header Cache-Control "public";
}

location ~* \.(html|htm)$ {
    expires -1;                  # 不设置缓存过期时间
    add_header Cache-Control "no-cache";
}

© 2023 - 2026 YEGUO