301重定向后如何防止chrome从磁盘缓存中加载index.html

Posted

技术标签:

【中文标题】301重定向后如何防止chrome从磁盘缓存中加载index.html【英文标题】:How to prevent chrome load index.html from disk cache after 301 redirect 【发布时间】:2019-05-27 08:10:50 【问题描述】:

每当我们发布网站的新版本时,chrome 缓存都会出现问题,我们搜索了几天并添加/删除了任何可能导致此问题的标头、元标记、nginx 配置等,或者据说已修复它,但什么都没有改变。 index.html 仍在缓存中,我们必须按 F5 才能查看随机计算机上的新更改,

该网站是作为 SPA 实现的,使用 angularjs 框架,并使用 traefik 代理后面的 ngnix 托管,使用 traefik 规则,我们通过 301 响应强制将 HTTP 请求重定向到 HTTPS。

今天我发现了失败的场景!如果用户在地址栏中输入 https 协议(例如https://example.com),一切正常,但如果用户返回并尝试访问http://example.com,chrome 将通过 301 重定向缓存将用户重定向到 https,然后加载index.html 的缓存版本,这不是我们想要的,可以缓存 301 重定向,但我们希望 chrome 从服务器获取 index.html,而不是从磁盘缓存中加载它!

注意:只要用户使用 HTTPS,索引从服务器加载或得到 304 响应,我们希望在用户仅输入域本身时发生这种情况,而不是使用 https。

这是添加到 index.html 的元标记:

<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="pragma" content="no-cache" />

这是我们的 nginx 配置的一部分:

...
http 
    ...
    proxy_cache_path /var/nginx/cache levels=1:2 keys_zone=prerender_cache:100m max_size=10g inactive=1d;
    proxy_cache_key "$request_method$host$request_uri$is_args$args";
    ...
    server 
        access_log /dev/stdout combined1;
        listen      80 default_server;
        server_name example.com;
        root /app;
        index  index.html;
        ...
        location ~ ^/(assets|static|styles) 
            expires     31d;
            add_header  Cache-Control public;
        
        location @asset_pass 
            root app/;
            try_files $uri =404;
        
        location / 
            expires -1;
            add_header Pragma "no-cache";
            add_header Cache-Control "no-store, no-cache, must-revalicate, post-check=0 pre-check=0";
            try_files $uri @prerender;
            autoindex on;
        
        location ~ \.html$ 
            expires -1;
            add_header Pragma "no-cache";
            add_header Cache-Control "no-store, no-cache, must-revalicate, post-check=0 pre-check=0";
        
    

现在的问题是:有没有办法解决这个问题或者这是谷歌浏览器的默认行为?

感谢大家抽出宝贵时间阅读此问题,如果问题太长,请见谅。

【问题讨论】:

这里是一个可能有帮助的问题的链接:***.com/questions/38196452/… @IBirle 感谢您的链接,但我们更喜欢非 js 的方式来解决这个问题,如果我们决定使用 js,我们可以实现一个强制重新加载功能,该功能检查最新的前端版本后端。 你找到方法了吗? @M-N @A.Anwin 不幸的是,不,我们使用我之前评论中描述的方法作为临时修复。 【参考方案1】:

您可以尝试touch您的index.html文件,然后响应头last-modified将更改为最新日期时间,因此浏览器会认为该资源“已过时”,将应用最新的301规则;

【讨论】:

我们已经在这样做了,我们也创建了新的 index.html,正如我在问题中提到的那样,不幸的是,Chrome 在特定情况下不会向服务器发送请求,而是从本地加载数据缓存。所以这行不通。

以上是关于301重定向后如何防止chrome从磁盘缓存中加载index.html的主要内容,如果未能解决你的问题,请参考以下文章

浏览器如何使用查询字符串缓存 301 重定向

Chrome 内存缓存与磁盘缓存

如何防止 301 重定向中的附加参数

如何防止 Chrome 将 AJAX 请求重定向到 HTTPS?

从客户端缓存中删除 http 301 重定向

302重定向