Search code examples
amazon-s3cachingcorsamazon-cloudfront

CloudFront CORS headers getting cached, resulting in cross origin problems


My website is loading images from an S3 Bucket which has the following configuration:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

This S3 bucket is connected to CloudFront distribution which has the following cache/origin policies: cache policy

origin policy

My website uses multiple domains, e.g. example1.com, example2.com, and it loads all the images perfectly. The problem begins when some libraries or SDKs try to access those images, I sometime, randomly, get cross origin error.

I think the problem is, that CloudFront caches the origin. So if a user tries to get image.jpg from example1.com, and then some other user tries to get image.jpg from example2.com, CloudFront cached origin example1.com to the request, and it will result in cross origin. To overcome this I'm using ?v=randomInt query param. This is bad practice though as I'm always getting a fresh copy of image.jpg and actually not using the cache.

Is there a way to NOT cache the origin headers, so both example1.com and example2.com can get image.jpg with their own origin? I tried removing the headers from the cache policy, but without any luck.

The error is as follows (after watermark.js tries to fetch the image with crossorigin="anonymous":

Access to image at 'https://cdn.treedis.com/tours/3453/tags/icons/8d2d0686-b3b9-4693-8167-0b652793c224.png' from origin example2.com has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

Once I add ?v=1234 to the URL of the image, it works fine. So it must be the cache.


Solution

  • Since you've already included Origin in your cache key, I don't think you will encounter this problem any more. Just create an invalidation of path /*, and the problem will hopefully be resolved.