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

AWS CDK部署Angular到CloudFront/S3(无S3静态网站托管)如何全路径重定向到index.html

问题根因

你遇到的403 Access Denied报错是因为Angular属于单页应用(SPA),所有路由逻辑都在客户端侧执行。当你直接访问/login/callback这类子路径时,CloudFront会默认向S3源站请求对应路径的实体文件,而你的S3桶中只存在index.html等静态构建产物,不存在名为login/callback的文件,S3就会返回访问拒绝错误。你配置的defaultRootObject仅对根路径/生效,无法覆盖子路径请求。

解决方案

在CloudFront Distribution配置中添加自定义错误响应规则,将S3返回的403、404错误都重定向到index.html,同时返回200状态码,让Angular客户端接管路由逻辑即可。该方案不需要开启S3静态网站托管,也不需要将S3桶设为公开访问,完全符合你的安全规范要求。

修改后的CDK代码示例

import { Duration } from 'aws-cdk-lib';

// 原有Bucket、BucketDeployment配置保持不变

const cloudFront = new Distribution(this, "CloudFront", {
  defaultBehavior: {
    origin: new S3Origin(bucket),
    viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
  },
  domainNames: [this.frontendFQDN],
  certificate: this.certificate,
  priceClass: PriceClass.PRICE_CLASS_100,
  defaultRootObject: "index.html",
  // 新增自定义错误响应配置
  errorConfigurations: [
    {
      errorCode: 403,
      responsePagePath: "/index.html",
      responseHttpStatus: 200,
      ttl: Duration.seconds(0)
    },
    {
      errorCode: 404,
      responsePagePath: "/index.html",
      responseHttpStatus: 200,
      ttl: Duration.seconds(0)
    }
  ]
})

配置说明

配置中ttl设为0是为了避免CloudFront缓存错误响应,调试阶段建议保持该配置,生产环境可根据缓存策略需求调整数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:15:04