Cloudfront passes request to incorrect origin if AllViewer origin policy is enabled

Viewed 202

I created a cloudfront distribution with the below details:

  • Origin1 -> S3Bucket
  • Origin2 -> APIGateway endpoint with base /Prod appended
  • DefaultBehavior -> *, Origin1, CachingEnabled, no Origin Policy
  • APIBehavior -> /api/*, Origin2, CachingDisabled

With the above setup, I see the desired behavior i.e., all requests to any path starting with /api/ is redirected to Origin2 and the rest to Origin1. Also the caching policy works fine.

But now I wish to forward headers/query parameters to origin without affecting the caching schema. So for Origin2's behavior (/api/*), I added AllViewer Origin policy (Forwards all headers, query requests etc.). But now the /api/* calls are redirected to Prod/api/* and Origin1 is used instead of Origin2.

This seems so counterintuitive to me, could anyone please enlighten if I'm missing something?

2 Answers

Hope you're doing well.

Regarding your inquiry, it seems like the managed origin request policy AllViewer is the culprit. If you use AllViewer policy, it forwards the host header to your origin. Please refer to the response below:

Let's say your configuration is like:

  • DefaultBehavior (*) -> Origin1(S3Bucket)
  • APIBehavior (/api/*) -> Origin2(APIG/w endpoint with base /Prod appended)

The request flow would be:

  1. example.com/api/getdata --(Host: example.com)--> CloudFront

Match the APIBehavior (/api/*) path behavior, CloudFront append the path and forward the request.

  1. CloudFront --(Host: example.com)--> example.com/Prod/api/getdata

example.com is a custom domain of your CloudFront distribution; it will go back to you CloudFront distribution again.

  1. example.com/Prod/api/getdata --(Redirect)--> CloudFront

Match the DefaultBehavior (*), CloudFront use Origin1(S3Bucket)

  1. CloudFront --(Forward request/Prod/api/getdata)--> Origin1(S3Bucket)

To fix it, I'll suggest you should create a new origin request policy which forwards the necessary headers and query strings only.

Note: If you make you origin to service like S3 or APIG/w, please don't forward the host header. It will cause some unexpected behaviors.

I hope this information has been helpful Feel free let me know if you have any question

I am facing the same issue. My problem is that the only header I need to have forwarded to the API is the Authorization header, and there are special rules in CloudFront preventing the Authorization header from being forwarded to the target unless all headers are forwarded. I also cannot add the Authorization header to the cache key if the cache is set to not cache anything.

If you switch to use the 'Legacy Cache Settings' and include the desired headers etc and then set the TTL to 0 it seems to act as expected.

Related