I am using AWS Amplify and cannot figure out how to configure my rewrite and redirects or routes.js to prevent trailing slashes from breaking my functionality.
When I run my code locally and try to visit localhost:3000/foo/bar/id
the page renders fine. When I deploy this same code through amplify and user clicks a button with an href, the browser gets a 302
and redirects the user to example.com/foo/bar/id/
, then because this page doesn't exist, the default Amplify redirect sends them to index.html
with a 404
I have tried adding the following to my react routes:
/foo/bar/:id
/foo/bar/:id/
and the following redirect rules in the AWS Amplify console:
/foo/bar/<id> | /foo/bar/<id> | 302
/foo/bar/<id>/ | /foo/bar/<id> | 302
but nothing is working. I am losing my mind here, any suggestions?
Amplify adds a trailing slash to prevent urls like /about.html
but that's probably not the real cause. Your app/browser is making requests to the server with routes that don't exist server-side (you're using SPA routes which are strictly client-side). Try adding the following redirect rule in the amplify js console (under App Settings: Redirects and rewrites > Edit > Open Text Editor):
[
{
"source": "</^[^.]+$|\\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf|map|json)$)([^.]+$)/>",
"target": "/",
"status": "200",
"condition": null
}
]
This rewrites all files to /index.html
which is the only route that exists server-side. For more info, checkout the docs on Trailing Slashes and Redirects for SPAs.
Here is a picture about how to do this settings in the aws amplify:
It is better that we copy the JSON object in the provided text editor.
Otherwise if you are going to use the webform please take care that you must enter this string as source:
</^[^.]+$|\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf|map|json)$)([^.]+$)/>
the reason is webform will scape the backslashes!
I had the same issue with my Next.js site on Amplify. After testing around for a few hours I've found the following solution:
[{
"source": "/report/<slug>/",
"target": "/report/<slug>",
"status": "200",
"condition": null
},
{
"source": "/report/<slug>",
"target": "/report/<slug>.html",
"status": "200",
"condition": null
}]
Add this to your redirects, then it should work.
You just have to replace "report" with your url parts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With