我们的 React 应用程序出现了缓存问题。
问题
这个问题自项目开始以来就一直存在,因为我们没有包括任何缓存头... 我们的客户总是需要在新的生产发布后刷新他们的网页。解决方案是刷新页面之后就可以了,直到下一次发布。
我们希望解决这个问题,使得客户不需要在新的生产发布后刷新页面。
当前设置
该应用程序使用 Create-React-App 构建,并使用默认的缓存破坏实现 (filename.[hash].js/css)。 我们通过使用 unregister() 禁用了 serviceworker。 该应用程序在使用 docker 构建的 Nginx 上运行。
尝试修复前的旧 Nginx 配置:
server {
listen 443 ssl;
ssl_certificate /etc/nginx/ssl/server.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header Content-Security-Policy "default-src 'none'; connect-src 'self'; manifest-src 'self'; script-src 'self'; img-src 'self'; font-src 'self' https://fonts.gstatic.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; report-uri /csp/report" always;
server_tokens off;
root /usr/src/app;
index index.html index.htm;
location ~* /favicon.ico$ {
try_files $uri $uri/ /favicon.ico =404;
}
location ~* /manifest.json$ {
try_files $uri $uri/ /manifest.json =404;
}
location / {
try_files $uri $uri/ /index.html =404;
}
location ~ .(static)/(js|css|media)/(.+)$ {
try_files $uri $uri/ /$1/$2/$3 =404;
}
}
我们尝试过的事情:
我们尝试更改Nginx中index.html的头信息:
location / {
try_files $uri $uri/ /index.html =404;
add_header Cache-Control "no-cache, no-store, no-transform, must-revalidate, max-age=0";
add_header Pragma "no-cache";
add_header Expires "0";
}
我们期望这可以解决我们index.html的缓存问题。在Chrome中打开应用程序时,会打开旧版本。当我们按下F5时,Chrome加载带有Cache-Control标头的新版本。然后我们在Chrome中打开一个新标签页,它再次显示应用程序的旧版本。
一些有效的解决方法(但仅适用于支持的浏览器)是添加Clear-Site-Data标头。这至少告诉我们这是一个缓存问题。
location / {
try_files $uri $uri/ /index.html =404;
add_header Clear-Site-Data "\"cache\"";
}
在按下F5之后加载具有Cache-Control头的应用程序新版本后,这些是我们从Nginx获取的标题。
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 17 Dec 2021 08:51:33 GMT
Content-Type: text/html
Content-Length: 1113
Last-Modified: Thu, 16 Dec 2021 14:35:26 GMT
Connection: keep-alive
ETag: "61bb4eae-459"
Cache-Control: no-cache, no-store, no-transform, must-revalidate, max-age=0
Pragma: no-cache
Expires: 0
Accept-Ranges: bytes
Strict-Transport-Security: max-age=31536000
为什么Chrome仍然加载旧的Web应用程序,即使我们使用这些新的缓存标头加载了应用程序?
感谢您的建议/帮助。