Blueboye
Blueboye

Reputation: 1494

Refreshing page on S3 throws "access denied" error but not if I use the origin

I have a NextJS application hosted on AWS. I have configured my domain to point to Cloufront and it points to the S3 origin bucket. I have added this policy to my S3 bucket:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion"
            ],
            "Resource": "arn:aws:s3:::<mybucket>/*"
        }
    ]
}

I have made it public as well as Enabled the Static website hosting. I have also set the Default Object to be index.html in Cloudfront.

So what's happening is when I go to my domain, the homepage loads and as long as I click through the links I can reach the page. But as soon as I hit refresh, I get the S3 AccessDenied message. My folder structure is like this:

- /index.html

- /articles
-- index.html

-- /article1
---- /index.html

-- /article2
---- /index.html
.
.
.

Basically every path has its own index.html (common setup with NextJS). I read about a 404 issue also setup a 404 error page as mentioned in this question about 404. However it hasn't solved the problem.

I then tried access my site directly through the S3 origin URL and everything works as expected including the page refresh. So, I am thinking something between the mapping of my domain and S3 origin is not working but I am not sure what is it. Is it on Cloudfront or S3 policy or something else.

Please advice.

Upvotes: 1

Views: 2237

Answers (1)

Blueboye
Blueboye

Reputation: 1494

I figured it out. Since nobody was able to answer it I thought of putting what helped me. I have my website hosted on S3 with Static hosting enabled. I copied the origin url from there (without the http:// part). I then went to cloudfront and while setting up the origin, I pasted the S3 static URL (without the http:// part). DO NO PICK THE ORIGIN FROM THE DROPDOWN if you are hosting a static site. The dropdown list points to the REST API endpoints of S3 and that doesn't work in this case. More info here: https://aws.amazon.com/premiumsupport/knowledge-center/cloudfront-serve-static-website/

Upvotes: 1

Related Questions