'Cloudfront passes request to incorrect origin if AllViewer origin policy is enabled
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?
Solution 1:[1]
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/Prodappended)
The request flow would be:
- example.com/api/getdata --(Host: example.com)--> CloudFront
Match the
APIBehavior (/api/*)path behavior, CloudFront append the path and forward the request.
- 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.
- example.com/Prod/api/getdata --(Redirect)--> CloudFront
Match the
DefaultBehavior (*), CloudFront useOrigin1(S3Bucket)
- 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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
