The problem with most of the proposed solutions, especially the most popular answer, is that you never get a 404 error for non-existent backend resources. If you want to continue getting 404, refer to this solution
- I added a root path to all my routes (that's new to this solution)
e.g. all my route-paths start with the same front end root...
in place of paths /foo/baz, /foo2/baz I now have /root/foo/baz , /root/foo2/baz paths. - The choice of the front-end root is such that it does not conflict with any real folder or path at the back-end.
- Now I can use this root to create simple redirection rules anywhere, I like. All my redirection changes will be impacting only this path and everything else will be as earlier.
This is the redirection rule I added in my s3 bucket
[
{
"Condition": {
"HttpErrorCodeReturnedEquals": "404",
"KeyPrefixEquals": "root/"
},
"Redirect": {
"HostName": "mydomain.com",
"ReplaceKeyPrefixWith": "#/"
}
}
]
Or Even following
[
{
"Condition": {
"KeyPrefixEquals": "root/"
},
"Redirect": {
"HostName": "mydomain.com",
"ReplaceKeyPrefixWith": "#/"
}
}
]
- After this, /root/foo/baz is redirected to /#/foo/baz, and the page loads at home without error.
I added the following code on-load after my Vue app is mounted. It will take my app to the desired route. You can change router.push part as per Angular or whatever you are using.
if(location.href.includes("#"))
{
let currentRoute = location.href.split("#")[1];
router.push({ path: `/root${currentRoute}` })
}
Even if you do not use redirection at the s3 level, having a single base to all routes can be handy in whatever other redirections you may prefer. It helps the backend to identify that is not a request for a real back-end resource, the front-end app will be able to handle it.