通过nginx替换指纹文件时,在浏览器中过期资产缓存

10

我正在通过nginx提供单页面JavaScript应用程序,当我部署新版本时,我希望强制浏览器使它们的JS缓存失效并请求/使用最新版本。

例如,当我将服务器文件夹上的一个名称为my-app-8e8faf9.js的文件替换为名为my-app-eaea342.js的文件时,我不希望浏览器再从其缓存中拉取my-app-8e8faf9.js。但是当没有可用的新版本时,我仍然希望它们从缓存中读取资产。

如何在nginx配置中实现这一点? 这是我的现有配置:

server {
  listen 80;

  server_name my.server.com;

  root /u/apps/my_client_production/current;
  index index.html;

  # ~2 seconds is often enough for most folks to parse HTML/CSS and
  # retrieve needed images/icons/frames, connections are cheap in
  # nginx so increasing this is generally safe...
  keepalive_timeout 10;
  client_max_body_size 100M;

  access_log /u/apps/my_client_production/shared/log/nginx.access.log;
  error_log /u/apps/my_client_production/shared/log/nginx.error.log info;

  location / {
    try_files $uri $uri/ =404;

    gzip_static on;
    expires max;
    add_header  Cache-Control public;

  }

  # Error pages
  error_page 500 502 503 504 /500.html;
}
1个回答

4

通过更改资源网址来使缓存失效是一种常见的做法。

但为了使此方法有效,您需要确保html文件不会永久缓存,这样当这些名称发生更改时,浏览器就会有一些信息。

因此,需要将html和资源分开存放在不同的位置。匹配器可以根据存储方式而异,例如:

location / {
  try_files $uri $uri/ =404;
  gzip_static on;
  }

location ^~ /assets/ {
  gzip_static on;
  expires max;
  add_header Cache-Control public;
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接