Luis Carlos
Luis Carlos

Reputation: 43

React app SPA on S3 AWS while refreshing the page shows 404 page

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.

Upvotes: 4

Views: 6390

Answers (2)

Artem Kozlenkov
Artem Kozlenkov

Reputation: 1264

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

Upvotes: 11

Tamás Sallai
Tamás Sallai

Reputation: 3365

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.

Upvotes: 2

Related Questions