reactjs - static website hosted in s3: pages return 404 after refresh
问题描述
With this bucket policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::mypage.com/*"
}
]
}
I am deploying a website that is build by reactJS v16+ (react-router-dom v5), and when I open the url, it works perfectly, e.g. from mypage.com, the that goes to /list works fine. Url is loaded as mypage.com/list and the page content is displayed.
However on any child page that is not homepage, for example mypage.com/list, once I refresh the page with browser, it returns S3's 404:
404 Not Found
Code: NoSuchKey
Message: The specified key does not exist.
Key: list
I don't even know how to debug this... any idea?
解决方案
正如@Panther 在评论中提到的那样,正确的方法是在 S3 存储桶的静态 Web 托管配置中向 index.html 添加错误回退。
原因是当一个 URL 被命中(通过在浏览器中手动输入或刷新)时,它会在命中我们的存储桶之前向 S3 的根服务器(由 AWS 管理的服务器)发送一个到 /list 的请求。该 S3 服务器不知道这是否是一个 reactjs 应用程序,因此它进入存储桶以在我的存储桶的根目录中查找 /list,该目录不存在,因此它返回 404 错误。
但是,通过添加错误回退,现在当它得到 404 时,它将请求重定向到 index.html,react 应用程序定义并加载到该 index.html 中。在这种情况下,/list 将通过正常流程到达处理页面渲染的正确路由器,问题解决。
推荐阅读
- react-native - 表单输入中的文本组件
- python-3.x - python中指向lambda函数的指针
- php - Laravel 多重删除
- jquery - 将变量从 1 个事件处理程序传递到另一个
- jenkins-pipeline - 无法从 Jenkins Pipeline 将图像推送到 GCR
- vue.js - 试图将多个条件放在一个循环 vue.js 中
- javascript - 可共享模块的打字稿层次结构
- spring - :无法解析匹配的构造函数(提示:为简单参数指定索引/类型/名称参数以避免类型歧义)
- java - JXLS Transformer 对象未初始化
- javascript - 当我从服务器获取代码内容时,Summernote onImageUpload 不起作用