Search code examples
amazon-web-servicesamazon-cloudfront

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.


Solution

  • 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