ChUck_PrOg
ChUck_PrOg

Reputation: 481

How to setup CloudFront to have a custom error page per origin

I'm trying to deploy an Angular Application on AWS using S3 and Cloudfront. Our Angular App is communicating on a Spring application serving as our backend app that is residing on an EC2 instance. I have already configured our CloudFront to redirect /api requests to our backend and everything else to the frontend. Right now, I've setup Cloudfront's custom error response for 403 and 404's to return our angular's index.html. The problem is that when our fontend tries to send and API call to our backend and returns a 404 with a valid json response, instead of receiving the json. We get the index.html file.

What I'm trying to achieve is that if the user accesses http://somedomain.com/invalid-path, they get served with the index.html but if they try to API call to http://somedomian.com/api/v1/invalid-path they should get what the back-end server returns.

Upvotes: 23

Views: 10602

Answers (2)

Chris
Chris

Reputation: 1620

I had same problem and solved as follows:

  • Configure the S3 bucket to have 'Static website hosting' and set index.html as the 'Error document'.
  • Change the CloudFront origin to be a 'Custom Origin' pointing to the S3 static website endpoint rather than an 'S3 Origin' pointing directly at the S3 bucket.
  • The 'Error Pages' config can then be removed from the CloudFront distribution.

Upvotes: 12

A.Khan
A.Khan

Reputation: 4002

You can create Lambda Function Association of Event type Origin response to modify the status code and body content. You will want to add this in the CloudFront behaviors used for your front-end app. Here is the example.

You can add 302 header and redirect to a location (cache behavior) for static error page or you can attach content to response.body and change status code to 200.

More on Lambda@Edge

Upvotes: 12

Related Questions