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

部署新Angular应用至AWS Amplify时出现404页面问题求助

解决Angular应用部署到AWS Amplify后出现404的问题

核心原因

Angular是单页应用(SPA),所有路由由前端处理,但AWS Amplify默认会将非根路径的请求直接返回404,同时构建路径配置错误也会导致资源加载失败。以下是针对性的解决步骤:

1. 配置SPA重写规则

在项目根目录创建或修改amplify.yml文件,添加路由重写规则,让所有请求都指向index.html:

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm install
    build:
      commands:
        - ng build --prod --base-href /
  artifacts:
    baseDirectory: dist/my-project
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*
  rewriteRules:
    - source: /<*>.+
      target: /index.html
      status: 200

注意:如果你的Angular版本是14及以上,构建输出目录会是dist/my-project/browser,需要把baseDirectory改成这个路径;--base-href参数要匹配实际部署路径,比如部署在https://xxx.com/my-app/下,就改成--base-href /my-app/。

2. 确认路由策略配置

如果不想配置重写规则,可以切换为哈希路由(URL会带#),修改app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes, HashLocationStrategy, LocationStrategy } from '@angular/router';

const routes: Routes = [/* 你的路由配置 */];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }]
})
export class AppRoutingModule { }

3. 检查Amplify控制台设置

登录AWS Amplify控制台,进入你的应用:

  • 到「部署设置」页面,确认构建命令和amplify.yml里的一致;
  • 确认构建输出目录和baseDirectory配置匹配,避免资源找不到导致的404。

4. 重新部署

修改配置后,提交代码到GitHub,触发Amplify重新构建部署,验证是否解决404问题。

内容的提问来源于stack exchange,提问作者Willemien van Tonder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 17:41:08