'React App url parameter with S3 and CloudFront
My apologies if the information that I have provided is vague as I am not so experience with AWS and React.
I have a React Application being deployed on S3 and CloudFront as per what is suggested in the following link.
Use S3 and CloudFront to host Static Single Page Apps (SPAs) with HTTPs and www-redirects
So most of the things are working fine. I have 403 and 404 errors being redirected to index.html. However the issue comes in where I have query parameters in my url. eg. https://example.com/example?sample=123 when I enter the url in my browser the query string gets removed from the url. The end result I got is https://example.com/example I have read some articles about forwarding query parameters but it's not working for me.
AWS Documentation - Query String Parameters
Hope I will be able to get some advise here. Thanks in advance.
Solution 1:[1]
The example?sample=123
is redirected to example
because S3 sees example?sample=123
as path (a folder named example?sample=123
), it will throw 404
as there is no such folder.
As you have mentioned, you have configured 404 -> index.html
, the browser then goes back to example
, which is very likely the default page of your react app.
Overall it looks like your query string is being cleared, actually it is lost during the redirection.
The solution includes three parts:
React
You can follow these two great tutorials, one for NextJs and another for RCA.
The way it works is to detect#!
in the path, keep and store the query string after redirection.S3
As included in the two links above, you have to set the redirection rule of the S3 Bucket, to add a#!/
prefix before the path on 403 or 404, it helps React to determine which parts of the url include query string. You can configure it inProperties -> Static website hosting -> Redirection rules – optional
. You need to also setindex.html
as theIndex document
and enablestatic web hosting
with the correct permission configured.CloudFront
- In
General
, setDefault Root Object
toindex.html
, make sure you don't make it as/index.html
. - In
Origin
, setOrigin domain
to theS3 Static Web Hosting URL (http://[bucket-name].s3-website.[region].amazonaws.com
, do not choose the bucket itself. - In
Behavior
, changeViewer
toRedirect HTTP to HTTPS
, setOrigin request policy - optional
toAllViewer
to let all query strings go through.
Hope it helps.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |