2

I am using AWS S3 static web hosting for my VueJs SPA app. I have setup routing rules in S3 and it works perfectly fine when I access it using S3 static hosting url. But, I also have configured CloudFront to use it with my custom domain. Since single page apps need to be routed via index.html, I have setup custom error page in cloudfront to redirect 404 errors to index.html. So now routing rules I have setup in S3 no longer works.

What is the best way to get S3 routing rules to work along with CloudFront custom error page setup for SPA?

Raja
  • 1,317
  • 3
  • 16
  • 22
  • You don't. You just set the `404` and `403` in CloudFront to go to `index.html` with a `200` so all routes are sent there and you handle it. Ignore S3 routing. – Ohgodwhy Oct 31 '18 at 01:36
  • If it works fine with the bucket endpoint, why do you need to enable the custom error overriding hack in CloudFront? Also, verify that you didn't [specify the bucket endpoint incorrectly](https://stackoverflow.com/a/34065543/1695906). – Michael - sqlbot Oct 31 '18 at 08:12

1 Answers1

4

I think I am a bit late but here goes anyway,

Apparently you can't do that if you are using S3 REST_API endpoints (example-bucket.s3.amazonaws.com) as your origin for your CloudFront distribution, you have to use the S3 website url provided by S3 as the origin (example-bucket.s3-website-[region].amazonaws.com). Also, objects must be public you can't lock your bucket to the distribution by origin policy.

So,

  • Objects must be public.
  • S3 bucket website option must be turned on.
  • Distribution origin has to come from the S3 website url, not the rest api endpoint.

EDIT:

I was mistaking, actually, you can do it with the REST_API endpoint too, you only have to create a Custom Error Response inside your CloudFront distribution, probably only for the 404 and 403 error codes, set the "Customize Error Response" option to "yes", Response Page Path to "/index.html" and HTTP Response Code to "200". You can find that option inside your distribution and the error pages tab if you are using the console.

Carlos E.
  • 41
  • 4
  • This works also for Blazor Webassembly app. I had similar case when being redirected back to cloudfront url from openidconnect provider. Was getting generic Access Denied from s3 because it was looking for full url as path rather than letting SPA parse it as a route. Once I added the rule as described here it forwarded callback to SPA for parsing and everything worked great. – Derek Feb 19 '21 at 18:29
  • 1
    This works for our React SPA (and is what I'm using) until you genuinely want a 404/403 error. – Ian Grainger Jun 10 '22 at 09:14