aws-amplify / aws-amplify/amplify-hosting

404 rewrite not working for SPAs like React

Open
#2,524 9 comments 3 reactions 1 assignee Claimed by @josefaidt View on GitHub
bug redirects
Dominant language
Dockerfile
Stars
481
Forks
123
PR merge metrics
No merged PRs in 30d

Description

### Before opening, please confirm:

- [X] I have checked to see if my question is addressed in the [FAQ](https://github.com/aws-amplify/amplify-console/blob/master/FAQ.md).
- [X] I have [searched for duplicate or closed issues](https://github.com/aws-amplify/amplify-console/issues?q=is%3Aissue+).
- [X] I have read the guide for [submitting bug reports](https://github.com/aws-amplify/amplify-console/blob/master/CONTRIBUTING.md).
- [X] I have done my best to include a minimal, self-contained set of instructions for consistently reproducing the issue.

### App Id

d31a6aysrans3d

### Region

us-east-1

### Amplify Console feature

Redirects

### Describe the bug

Setting up a 404 rewrite via Amplify for SPAs like React, is not working. Instead of sending a HTTP status code of 404, a 200 is returned after the redirect.

### Expected behavior

404 rewrite should send the 404 status code instead of 200

### Reproduction steps

1. Setup 404 rewrite on Amplify with source: `/not-found` and target: `/error.html`
2. Setup a catch-all route in React that does a redirect: `window.location.href = "/not-found";`

Basically, when React sees any route that is not already defined, it will redirect the user to `/not-found`. This request will come to Amplify distribution, where we will rewrite the HTTP status to 404 and send the user back to `/error.html`.

First, set this up as the Rewrite rules on Amplify:

```
[
{
"source": "/not-found",
"target": "/error.html",
"status": "404-200",
"condition": null
},
{
"source": "",
"target": "/index.html",
"status": "200",
"condition": null
}
]
```

Then, create `NotFoundRedirect` function:
```
const NotFoundRedirect = () => {
window.location.href = "/not-found";
};

export default NotFoundRedirect;
```

Then, add these routes in `App.js`:
```

```

Here's the full implementation in my Github repo: https://github.com/Narrator/reactRoutesAmplify

---

### Build Settings

_No response_

### Additional information

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.