4

I have a SPA made with React JS on a S3 Bucket and I’m using Cloud Front to work through HTTPS and with a custom domain. When I refresh the page - if I have another Route that is not the BASE_URL (for example domain.com/something), S3 sends me a 404 error.

I also tried redirecting the error page to BASE_URL but it doesn’t work, it redirects me to the Http default domain that S3 provides me and again, it gives me an 404 error page.

I don’t know if there exists an alternative way to keep the URL without any change (domain.com/page) and avoid the 404 error the way a web server (apache) handles.

1
  • Does this solve your issue?
    – jellycsc
    Sep 21, 2020 at 23:50

2 Answers 2

7

If you are using CloudFront to host s3 website, the effective way to get rid of 404 on reload of non-index route like www.google.com/about or similar non / is by the following steps:

  1. Go to your CloudFront distribution
  2. Go to Error Pages
  3. Create a new error page with the following params:
    HTTP Error Code: 404
    TTL: 0
    Custom Error Response: Yes
    Response Page Path: /index.html
    HTTP Response Code: 200

enjoy

credits going to this article https://gist.github.com/bradwestfall/b5b0e450015dbc9b4e56e5f398df48ff

1

You have two options. Either use CloudFront error page as a catch-all that redirects to / (you mentioned you tried setting an error page but did not detail what you did. This should work). The downside is that it will respond with the HTML page for all not found paths, even for mistyped CSS paths, for example.

The other solution is to use Lambda@Edge to rewrite the origin request path. This is a more customizable solution and you can define which paths you want to redirect to the root.

2
  • Do you happen to have an example of such a Lambda@Edge?
    – obax
    Dec 29, 2022 at 18:26
  • 1
    Unfortunately, no. Though AWS released CloudFront functions that provide an easier alternative to this than Lambda@Edge: aws.amazon.com/blogs/aws/… Dec 30, 2022 at 21:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.