如何将 CloudFront 设置为每个来源都有一个自定义错误页面

How to setup CloudFront to have a custom error page per origin

我正在尝试使用 S3 和 Cloudfront 在 AWS 上部署一个 Angular 应用程序。我们的 Angular 应用程序正在 Spring 应用程序上进行通信,该应用程序充当驻留在 EC2 实例上的后端应用程序。我已经将我们的 CloudFront 配置为将 /api 请求重定向到我们的后端,并将其他所有请求重定向到前端。现在,我已经将 Cloudfront 的 403 和 404 自定义错误响应设置为 return 我们的 angular 的 index.html。 问题是 当我们的 fontend 尝试发送和 API 调用我们的后端并且 returns 一个具有有效 json 响应的 404,而不是收到json。我们得到 index.html 文件。

我想要实现的是,如果用户访问 http://somedomain.com/invalid-path, they get served with the index.html but if they try to API call to http://somedomian.com/api/v1/invalid-path,他们应该得到后端服务器 returns.

您可以创建事件类型Origin response的Lambda函数关联来修改状态码和body内容。您需要将其添加到用于您的 front-end 应用程序的 CloudFront behaviors 中。 Here 就是例子。

您可以添加 302 header 并重定向到静态错误页面的位置(缓存行为),或者您可以将内容附加到 response.body 并将状态代码更改为 200。

More on Lambda@Edge

我遇到了同样的问题,解决方法如下:

  • 将 S3 存储桶配置为具有 'Static website hosting' 并将 index.html 设置为 'Error document'。
  • 将 CloudFront 来源更改为 'Custom Origin' 指向 S3 静态网站端点,而不是 'S3 Origin' 直接指向 S3 存储桶。
  • 然后可以从 CloudFront 分发中删除 'Error Pages' 配置。