nginx 的单页应用程序 (SPA) 缓存配置

Single page app (SPA) cache config for nginx

我在服务器上有一个小型单页应用程序 运行,每次我对其进行更改时,一些用户都会在他们的浏览器上报告错误。这些错误在清除历史记录后消失,这意味着部分 SPA 已被缓存。我在 SPA 主页上添加了 no-cache 标签。

server {
  listen 80;
  client_max_body_size 25M;
  server_name [COMMENTED_OUT];
  access_log /var/log/nginx/access_log.log;
  error_log /var/log/nginx/error_log.log;
  server_tokens off;
  location / {
    try_files $uri /static/index.html;
    add_header Cache-Control no-cache;
  }
  location /static/ {
    autoindex off;
    alias /static/;
  }
}

我在这方面做错了什么吗?

您可以选择性地设置过期时间:

map $sent_http_content_type $expires {
  default                     off;
  text/html                   epoch;
  text/css                    1d;    # based on mime type
  application/javascript      1d;
  ~image/                     max;   # based on path
}

在您的站点配置之上,在服务器指令之外声明它。然后在服务器配置中添加:

server {
   ...
   expires $expires;
   ...
}