首页 > 解决方案 > 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?

标签: reactjsamazon-s3react-router-dom

解决方案


正如@Panther 在评论中提到的那样,正确的方法是在 S3 存储桶的静态 Web 托管配置中向 index.html 添加错误回退。

原因是当一个 URL 被命中(通过在浏览器中手动输入或刷新)时,它会在命中我们的存储桶之前向 S3 的根服务器(由 AWS 管理的服务器)发送一个到 /list 的请求。该 S3 服务器不知道这是否是一个 reactjs 应用程序,因此它进入存储桶以在我的存储桶的根目录中查找 /list,该目录不存在,因此它返回 404 错误。

但是,通过添加错误回退,现在当它得到 404 时,它将请求重定向到 index.html,react 应用程序定义并加载到该 index.html 中。在这种情况下,/list 将通过正常流程到达处理页面渲染的正确路由器,问题解决。


推荐阅读