You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 15部署GCloud遇URL未找到问题,仅HashLocationStrategy可用

解决Angular 15部署GCloud App Engine时非Hash路由404问题

问题描述

部署Angular 15到GCloud App Engine后,只有启用HashLocationStrategy时网站能正常访问,直接访问带路径的URL(如website.com/home)会返回以下错误:

Error: Not Found
The requested URL /home was not found on this server.

问题根源

Angular默认的PathLocationStrategy(无Hash路由)是前端路由,所有路由逻辑由Angular在浏览器端处理。但GCloud App Engine的默认配置会尝试在服务器上寻找对应路径的物理文件,找不到就返回404,不会自动将请求转发到单页应用的入口index.html。而HashLocationStrategy通过#分隔路由,服务器只会处理#之前的根路径,路由部分由前端处理,因此不会触发404。

解决方案

1. 修改app.yaml配置,配置请求重定向

更新handlers规则,先匹配所有静态资源,再将剩余所有请求转发到index.html:

runtime: python27
api_version: 1
threadsafe: true
handlers:
  # 匹配所有静态资源文件(js、css、图片、字体等)
  - url: /(.*\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot))$
    static_files: dist/pocket-mechanic/\1
    upload: dist/pocket-mechanic/(.*\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot))$
    secure: always
  # Catch-all规则:所有其他请求都转发到index.html
  - url: /.*
    static_files: dist/pocket-mechanic/index.html
    upload: dist/pocket-mechanic/index.html
    secure: always

skip_files:
  - e2e/
  - node_modules/
  - src/
  - coverage
  - ^(.*/)?\..*$
  - ^(.*/)?.*\.json$
  - ^(.*/)?.*\.md$
  - ^(.*/)?.*\.yaml$
  - ^LICENSE

2. 恢复Angular默认路由配置

移除HashLocationStrategy相关配置,使用默认的PathLocationStrategy:

app.routing.module.ts

@NgModule({
  imports: [RouterModule.forRoot(routes)], // 移除{useHash: true}
  exports: [RouterModule],
})
export class AppRoutingModule { }

app.module.ts

providers: [
   AuthService,
   // 移除{provide: LocationStrategy, useClass: HashLocationStrategy}
],

3. 重新部署应用

执行GCloud部署命令重新发布应用:

gcloud app deploy

完成以上步骤后,访问website.com/home这类路径时,服务器会将请求转发到index.html,由Angular前端处理路由,即可正常访问。

内容的提问来源于stack exchange,提问作者chumberjosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 14:43:31