'CloudFront works initially then AccessDenied error

I have a CloudFront distribution setup that points to an S3 bucket whose purpose is to host a website. Whenever I go to a nested page: /path1/path2, the page renders fine. If I refresh the page, I get presented with:

<Error>
    <Code>AccessDenied</Code>
    <Message>Access Denied</Message>
    <RequestId>89F25EB47DDA64D5</RequestId>
    <HostId>Z2xAduhEswbdBqTB/cgCggm/jVG24dPZjy1GScs9ak0w95rF4I0SnDnJrUKHHQC</HostId>
</Error>

The website is hosted on a private S3 bucket that can only be accessed via an OAI, that has the following permissions:

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "PolicyForCloudFrontPrivateContent",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E1XXXXXXXXX"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::frontend-bucket-XXXXXXXXXXXX/*"
        },
        {
            "Sid": "Enforce SSL",
            "Effect": "Deny",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::frontend-bucket-XXXXXXXXXXXX",
                "arn:aws:s3:::frontend-bucket-XXXXXXXXXXXX/*"
            ],
            "Condition": {
                "Bool": {
                    "aws:SecureTransport": "false"
                }
            }
        }
    ]
}

I've read a tonne of StackOverflow questions about people experiencing the same issue. Here's what I've tried so far (nothing worked):

  • Changed bucket name from <website bucket>.s3.us-west-2.amazonaws.com to <website bucket>.s3-website-us-west-2.amazonaws.com
  • Added custom responses for 404 & 403 error to return a 200 response, with a response page path of /index.html and 0 TTL. Instead of returning an AccessDenied XML formatted page, it returns blank pages.
  • I've added an invalidation to the /* paths

Again, whenever I hit the URL of nested pages path the first time it works fine. If I'm just hitting the base URL with no nested paths, I don't run into this issue at all. When I refresh that same page, that's when things break. What am I doing wrong?



Solution 1:[1]

This is not an issue with cloudfront or s3 as long as you have made the objects in the s3 bucket public and cloudfront is pointing right. This is a very common case when people try to host react based websites on the s3 bucket. This can be solved by multiple methods one of them are :-

While configuring your s3 bucket to be served as static website, just point the error document to index.html

setting up static web site rules

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 manigedit