s3中托管的静态网站:刷新后页面返回404 [英] static website hosted in s3: pages return 404 after refresh

查看:195
本文介绍了s3中托管的静态网站:刷新后页面返回404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此存储桶策略:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicReadGetObject",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::mypage.com/*"
        }
    ]
}

我正在部署一个由reactJS v16 +(react-router-dom v5)构建的网站,当我打开url时,它可以正常工作,例如从mypage.com,转到/list的效果很好.网址已加载为mypage.com/list,并显示了页面内容.

但是,在不是主页的任何子页面上,例如mypage.com/list,一旦我使用浏览器刷新页面,它就会返回S3的404:

404 Not Found

    Code: NoSuchKey
    Message: The specified key does not exist.
    Key: list

我什至不知道该如何调试...任何想法?

解决方案

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

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

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

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?

解决方案

As @Panther mentioned in the comment, the right way to go is to add an error fallback to index.html in the S3 bucket's static web hosting configuration.

The reason of this is when a URL is hit (either by manual input in the browser or a refresh), it sends a request to /list to the S3's root server (the one managed by AWS) before it hits our bucket. That S3 server have no idea if this is a reactjs app or not, so it goes into the bucket to look for the /list in the root of my bucket, which doesn't exist, so it returns the 404 error.

However by adding the error fallback, now when it gets 404, it redirects the request to index.html, where the react app defined and loaded into. In this case, the /list will go through the normal flow to reach the right router that handles page rendering, problem solved.

这篇关于s3中托管的静态网站:刷新后页面返回404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆