Angular PWA Service Worker离线模式加载index.html异常问题
问题背景
- Angular版本:14.0.3
- @angular/service-worker版本:14.2.0
- 使用
ng add @angular/pwa配置PWA,ngsw-config.json配置如下:
{ "$schema": "../../node_modules/@angular/service-worker/config/schema.json", "index": "/index.html", "assetGroups": [ { "name": "app", "installMode": "prefetch", "resources": { "files": [ "/favicon.ico", "/index.html", "/manifest.webmanifest", "/*.css", "/*.js" ], "urls": [] } }, { "name": "assets", "installMode": "prefetch", "updateMode": "prefetch", "resources": { "files": [ "/assets/**", "/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)" ] } } ] }
本地localhost:8080环境下应用离线模式正常,但部署到服务器后,离线时尝试加载index.html报错:Failed to load resource: the server responded with a status of 504 ()
解决步骤
检查服务器路由重定向配置
Angular是单页应用,所有路由请求都需要重定向到index.html,否则离线时非根路径请求会触发服务器返回错误。- Nginx配置示例:
location / { try_files $uri $uri/ /index.html; } - Apache配置示例:
RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]
- Nginx配置示例:
验证Service Worker状态与缓存
打开浏览器开发者工具→Application→Service Workers,确认SW已激活且处于"activated and is running"状态;进入Cache Storage,检查ngsw:app分组下是否包含index.html、主js/css文件等核心资源。如果缓存缺失,可尝试清除浏览器缓存后重新加载应用,触发SW重新缓存。调整服务器对SW文件的缓存策略
确保ngsw-worker.js不被服务器缓存,否则旧的SW可能无法正确处理新部署的资源。配置服务器对该文件设置响应头:Cache-Control: no-cache, no-store, must-revalidate Pragma: no-cache Expires: 0确认部署路径匹配配置
如果应用部署在服务器的子路径下(如https://example.com/my-app/),需修改ngsw-config.json中的index路径为/my-app/index.html,同时assetGroups里的资源路径也要对应调整为子路径开头(如/my-app/assets/**)。排查服务器网关/代理配置
504是网关超时错误,可能是服务器的代理或网关在离线时仍尝试转发请求到后端服务,需确保服务器配置允许Service Worker完全接管离线请求,无需转发到后端。
内容的提问来源于stack exchange,提问作者dritan

