- Newest
- Most votes
- Most comments
This is a common issue when serving single-page applications (SPAs) like Next.js builds through CloudFront and S3. The problem occurs because CloudFront is looking for an exact match of the requested path in S3, which doesn't exist for routes like '/some-page/'.
To resolve this, you can implement a CloudFront function or Lambda@Edge to rewrite the URL requests. This function would add 'index.html' to the end of URLs that don't have a file extension, allowing CloudFront to serve the correct content for all routes.
Here's a step-by-step solution:
-
Create a CloudFront function that checks if the request is for a file (has an extension) or a directory (ends with '/'). If it's neither, append '/index.html' to the request.
-
Attach this function to the CloudFront distribution's origin request event.
-
Ensure your S3 bucket policy allows CloudFront to access objects using the OAC (Origin Access Control).
-
Double-check that your CloudFront distribution's default root object is set to 'index.html'.
-
Verify that your Next.js build is correctly generating the necessary files in your S3 bucket.
By implementing this solution, you should be able to reload any page of your application without encountering access denied errors, and without needing to manually add '/index.html' to the URL.
Remember, when using OAC with CloudFront, you're correct in not enabling static website hosting on the S3 bucket. The function will handle the URL rewriting that the static website hosting would typically manage.
This approach provides a clean URL structure for your website while maintaining the underlying file organization in your S3 bucket and leveraging the security benefits of OAC.
Sources
S3/Cloudfront & OAC: Access denied when accessing path other than index site | AWS re:Post
How to redirect URL paths in CloudFront with S3 Bucket? | AWS re:Post
Access Denied for CloudFront to S3 static site | AWS re:Post
Relevant content
- asked 5 months ago