Recently, we at Alpe Audio launched a new service, called Example Finder, as part of our efforts to expose more parts of our content creation engine externally.
Using Next.js as our go to framework for React Apps, we encounter the issue of accessing URLs inside the app, not from the main page. When refreshing or sending a link to pages like /page1 you’ll get a 403 error.
This is really bad both for usability (sending to friends specific pages) and for SEO (google can’t index the internal pages).
I found this great guide by Mark Biek explaining how to fix it for react js apps. Since we are using Next.js, and things changed a bit since he wrote it we had to do some tweaks. I wrote this for future internal and external reference.
Assuming you already have a react.js website hosted on s3, you need to first change the S3 Routing Rules in S3 bucket -> Properties -> Static website hosting -> Redirection rules.
The new s3 console changes the routing rules format to JSON, so you’ll need to add this (don’t forget to replace myhost.com):
These rules add #!/ as the prefix to the URL in the case of a 403 or 404 error. This solves the react-router issue and now it will load the right page.
Now, we would like to remove this prefix from the URL for a cleaner solution. You’ll need to edit your _app.js and add:
If you use CloudFront the redirect rules won’t work since the service access the bucket directly.
In order to solve it, change the CloudFront origin to the static hosting URL and not the bucket.
it’s working 👍