I have an angular 6 website hosted on S3 with S3 website hosting enabled. Also, I have a CloudFront distribution in front of it. I configured cloud front so that it redirects anything to index.html and responses with 200.
However, only "/" can be accessed using CloudFront. Other urls such as "/*" are not loading. Angular loads "/" this instead. As if angular sees only "/".
I added some code to log the url passed to angular and it turns out to be always "/".
Also, some other times "/*" urls don't even load "/" and I see this error on console "Uncaught SyntaxError: Unexpected token <".
Do you guys have any idea what could be causing this?
S3 Settings
Cloud front behavior:
Open the CloudFront console. Choose Create Distribution. Under Origin, for Origin domain, choose your S3 bucket's REST API endpoint from the dropdown list. Or, enter your S3 bucket's website endpoint.
Amazon CloudFront works with S3 but copies files from S3 to the outer "edge" of Amazon's servers, allowing for fast retrieval. My tests show that it retrieves files in about half the time of S3. There's a slight increase in price from Amazon S3, but not much.
CloudFront is another service often used (and recommended) with S3 when you're trying to distribute files digitally all over the globe. CloudFront is a CDN from Amazon with edge servers all over the world. This is how it works: Your user, say from India, tries to load your website whose server is located in the USA.
Please have a look at : how to deploy react and angular apps to S3/Cloudfront
Have you created a custom behavior for 403 (Forbidden) and 404 (not found) responses?
Every time that someone does a request to your website, for example, www.yourwebsite.com/routeuri, note that this URI routeuri does not exist in your ORIGIN (which is S3 BUCKET), so your origin (S3 BUCKET) will return 403 response (Forbidden). So you should also added a custom error response for 403 status code, as shown in image below:
Please also make sure that your also added index.html as a Default Root Object in both Cloudfront and S3 Bucket as shown by images below:
I really recommend read official documentation to understand about CloudFront relationship with origin.
In my case this could be solved by adding index.html as the 'error document' under 'static website hosting'. Nothing else.
This happened to me too and I fix it adding a custom error response in the CloudFront settings:
This happens because when you configure the CloudFront to be the only available access for the S3 bucket and you search /something, cloudfront will try to return that file to the user browser. Now the bucket is private and is only accessible from the CF, so this will return 403 or 404 error. To solve it, you need to return index.html when those errors happen.
Credits: https://lucasfsantos.com/posts/deploy-react-angular-cloudfront/
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