简体   繁体   中英

Javascript React Single Page Application + Amazon S3: Permalinks issue

I am using an S3 bucket as static web solution to host a single page React application. The react application works fine when I hit the root domain s3-bucket.amazon.com and the HTML5 history api works fine every time I click on a link the new url looks fine: _http://s3-bucket.amazon.com/entities/entity_id_ The problem happens when I use permalinks to access the application. Let's assume I am typing the same url (_http://s3-bucket.amazon.com/entities/entity_id_) in the browser I will get the following error from Amazon S3:

404 Not Found
Code: NoSuchKey
Message: The specified key does not exist.
Key: users
RequestId: 3A4B65F49D07B42C
HostId: j2KCK4tvw9DVQzOHaViZPwT7+piVFfVT3lRs2pr2knhdKag7mROEfqPRLUHGeD/TZoFJBI4/maA=

Is it possible to make Amazon S3 to work nicely with permalinks and HTML5 history api? Maybe it can act as proxy?

Thank you

Solution using AWS CloudFront:

Step 1: Go to CloudFront

Click on distribution id

Go to the Error page tab

Click on Create Custom Error Response

Step 2: Fill the form as

HTTP Error Code: 404

TTL: 0

Custom Error Response: Yes

Response Page Path: /index.html

HTTP Response Code: 200

source: https://medium.com/@nikhilkapoor17/deployment-of-spa-without-location-strategy-61a190a11dfc

Sadly S3 does not support the wildcard routing required for single page apps (basically you want everything after the host in the url to serve index.html, but preserve the route.

So www.blah.com/hello/world would actually serve www.blah.com/index.html but pass the route to the single page app.

The good news is you can do this with a CDN such as Fastly (Varnish) in front of S3. Setting up a rule such as:

if(req.url.ext == "" ) {
    set req.url = "/index.html"; 
}

This will redirect all non asset requests (anything without a file extension) to index.html on the domain.

I have no experience running SPA on Amazon S3, but this seems to be a problem of url-rewriting. It is one thing do have the history (html5) api rewrite your url when running your application / site. But allowing rewritten urls to be accessible when refreshing or cold-surfing to your site definitely needs url-rewriting on a server level. I'm thinking web.confg (IIS), .htaccess (Apache) or nginx site configuration.

It seems the same question already got asked some time ago: https://serverfault.com/questions/650704/url-rewriting-in-amazon-s3

Specify the same name for the index and error files on "Static website hosting" properties. See linked image 1 .

Old question but simplest way would be to use hash routing. So instead of mydomain.com/somepage/subpage it would be mydomain.com/#/somepage/subpage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM