【问题标题】:NGINX disable cache for service worker in SPANGINX 在 SPA 中禁用服务工作者的缓存
【发布时间】:2022-08-05 02:15:59
【问题描述】:

最好在每次需要时“强制”浏览器获取服务工作者文件,而不是从缓存中加载。 我正在使用 NGINX (1.21) 来提供我的 SPA 的静态文件,我的初始配置 (default.conf) 是:

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    # redirect server error pages to the static page /50x.html
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

我使用以下location 块来禁用缓存,仅为service-worker.js

location = /service-worker.js {
    add_header Cache-Control \'no-store, no-cache\';
    if_modified_since off;
    expires off;
    etag off;
}

在 Chrome DevTools 中清除应用程序缓存,然后硬重新加载后,浏览器收到 404 not found for service-worker.js,但其他一切正常。

我尝试了不同的“解决方案”,例如将 service worker 块移动到默认块之上、添加别名、添加不同的标头等,但每次它都返回 404。

    标签: nginx single-page-application service-worker nginx-location


    【解决方案1】:

    经过几个小时的调试和尝试不同的解决方案后,我发现了问题。

    location / 块有一个 root 指令告诉 nginx 静态文件在哪里。 我的假设是为服务工作者添加特定的location 块将应用该块中的所有内容以及默认的location / 块。看起来 NGINX 不能那样工作,所以简单的解决方案是在两个 location 块中复制 root 指令,并且在测试后它就像一个魅力。

    无需在每个location 块中重复此信息,因此root 指令可以移动到server 块下。

    最终配置文件为:

    server {
        listen       80;
        listen  [::]:80;
        server_name  localhost;
        root   /usr/share/nginx/html;
    
        #access_log  /var/log/nginx/host.access.log  main;
    
        location = /service-worker.js {
            add_header Cache-Control 'no-store, no-cache';
            if_modified_since off;
            expires off;
            etag off;
        }
    
        location / {
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }
    
        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-15
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      相关资源
      最近更新 更多