Firebase 托管:如何防止缓存 SPA 的 index.html

2024-02-26

我在 firebase 上托管一个 SPA,几乎所有路径都被重写为index.html。我正在使用基于 webpack 哈希的缓存清除,所以我想始终阻止缓存我的index.html但没有任何其他文件。我发现这样做非常困难。具体来说,我的文件布局如下所示

/
├── index.html
├── login.html
├── js
│   ├── login.ba22ef2579d744b26c65.bundle.js
│   └── main.6d0ef60e45ae7a11063c.bundle.js
└── public
    └── favicon-16x16.ico

我天真地开始了"sources": "index.html"在阅读文档中的这段引用之前。

每个定义都必须有一个与原始请求路径匹配的源密钥,无论使用什么重写规则全局表示法 https://firebase.google.com/docs/hosting/full-config#section-glob.

好吧,所以我想我需要一个路径,而不是一个简单的 glob 来指定我想要这些标头的文件。由于大多数路径重定向到index.html,我需要一个排除所有我不想放置这些标头的路径的全局变量。

作为参考,我的firebase.json托管部分如下所示:

{
  "hosting": {
    "public": "dist",
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ],
    "cleanUrls": true,
    "trailingSlash": false,
    "headers": [
      {
        "source": <<<WHAT-GOES-HERE?>>>,
        "headers": [
          {
            "key": "Cache-Control",
            "value": "no-cache, no-store, must-revalidate"
          },
          {
            "key": "Pragma",
            "value": "no-cache"
          },
          {
            "key": "Expires",
            "value": "0"
          }
        ]
      }
    ]
  }
}

因此,举一些重定向到index.html并且不应该被缓存的例子

mysite.com  
mysite.com/  
mysite.com/foo/bar/baz  
mysite.com/index.html 

注意:如果最后一个被缓存,我还可以活下去,因为它在实践中没有被使用。

以及那些不重定向到index.html并且不应该被缓存的东西

**/*.* (ideally excluding index.html)
mysite.com/login  

我自己得到的最接近的是**/!(login|*.*)它几乎适用于上面列出的所有内容,但莫名其妙地不适用于mysite.com or mysite.com/。这两个页面没有被这个 glob 匹配,我不明白为什么。


这是我正在使用的配置。逻辑是对所有静态文件使用缓存,例如images, css, js等等..对于所有其他人,即"source": "/**"将缓存设置为无缓存。所以对于所有其他文件,也许example.com、example.com/index.html、example.com/about-us、example.com/about-us.html不会应用缓存。

{
  "hosting": {
    "public": "dist",
    "headers": [
      {
        "source": "/**",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "no-cache, no-store, must-revalidate"
          }
        ]
      },
      {
        "source":
          "**/*.@(jpg|jpeg|gif|png|svg|webp|js|css|eot|otf|ttf|ttc|woff|woff2|font.css)",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "max-age=604800"
          }
        ]
      }
    ],
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"]
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Firebase 托管:如何防止缓存 SPA 的 index.html 的相关文章

随机推荐