CDN (CloudFront) -> S3 的概念来提供静态文件。 我们已将 S3 配置为提-6ren">
gpt4 book ai didi

amazon-s3 - 如何解决SPA上的 "x-cache: Error from cloudfront"

转载 作者:行者123 更新时间:2023-12-02 23:50:01 26 4
gpt4 key购买 nike

我们在尝试使用客户端路由器( react 路由器)运行 SPA 时遇到问题。我们使用 DOMAIN -> CDN (CloudFront) -> S3 的概念来提供静态文件。

我们已将 S3 配置为提供静态文件。 CDN 配置为源自 S3,并且我们配置了自定义错误页面来捕获错误:

enter image description here

通过此配置,我们可以捕获如下错误:

https://www.example.com/custom-url

CDN 会将所有 404/403 错误重定向到主 index.html,而 react router 将获得正确的路由。

我们的网站正在运行,客户端路由器工作正常,但我们的 CDN 的响应出现问题,x-cache: Error from cloudfront:

enter image description here

如果我们在没有任何查询参数(不是查询字符串)的情况下访问主网址 https://www.example.com ,则一切正常。

如何解决这个问题并使我的所有动态 URL 都正常工作?

谢谢。

最佳答案

当您访问 http://mywebsite.com 时,请求将命中 S3 中的 index.html 文件。然后,您可以单击一个按钮并转到 http://mywebsite.com/stats,这是 SPA 应用程序的内部路由。因此,它不会触发任何后端请求。

但是,如果您重新加载页面,http://mywebsite.com/stats 将被发送到 S3,因为您的浏览器不知道您正在运行 SPA 前端。

S3 将通过 index.html 返回 403 错误,Cloudfront 将向您发送该错误。

解决方案是在 Cloudfront 中使用边缘 lambda 函数。这是一个例子:

const path = require('path')

exports.handler = (evt, ctx, cb) => {
const {request} = evt.Records[0].cf

if (!path.extname(request.uri)) {
request.uri = '/index.html'
}

cb(null, request)
}

来源:https://hackernoon.com/how-to-host-a-single-page-application-with-aws-cloudfront-and-lambda-edge-39ce7b036da2

关于amazon-s3 - 如何解决SPA上的 "x-cache: Error from cloudfront",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59160472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com