Search code examples
amazon-web-servicesamazon-s3amazon-cloudfront

CloudFront multi origin and cache behaviour issue


I have defined 2 S3 buckets as origins in CF.

Origin 1 : mybucket1.amazonaws.com
Origin 2 : mybucket2.amazonaws.com/images

I only want to distribute images folder in mybucket2.

I created a cache behaviour with the path pattern /images pointing to Origin2

I've tried to access the images using the url https://lksngfd4w24.cloudfront.net/images/image1.jpg

Seems like CF is appending the cache behaviour path pattern to the s3 path. Above url throws an error like below.

<Error>
<Code>NoSuchKey</Code>
<Message>The specified key does not exist.</Message>
<Key>
images/images/image1.jpg
</Key>
<RequestId>sdanfladnfaf</RequestId>
<HostId>
   medlakfmkamfldaf
</HostId>
</Error>

Is there a way to stop CF appending the path prefix to the S3 URL?. Or is there any other way to achieve this kind of requirement using a single distribution but with multiple origins.


Solution

  • For your requirement, add the both origins with base path and configure the behaviors such that

    • Default behavior for /* is Origin 1
    • Behavior /images/* overrides to Origin 2

    Note: In your Origin 2 it requires to have images folder for this to work which is a limitation with CloudFront behavior mappings to S3 origins.

    If you need further extensions you can do it using, Edge Lambda by changing the request URLs to different paths in origin.