amazon-s3http-headerscorscdn

Getting S3 to always include a Vary header in its response


I have CORS headers set up on S3, and when a browser makes a CORS request (i.e. includes an Origin header), S3 adds all the right headers to the response, including a Vary header. However, if the request does not include an Origin header, the response does not include a Vary header, which leaves intermediate caches (such as CDNs) free to cache the response and serve it when a later request comes in, even if that later request adds an Origin header.

How can I get S3 to always return a Vary header?


Solution

  • Newer answer from 2025:

    S3 and CloudFront have come a long way since 2014, including having added support for both Lambda@Edge as well as CloudFront Functions since then.

    Those are better solutions these days.

    Original answer from 2014:

    The why is long-winded, but the short answer is: you can't. Not currently, anyway.

    [TL;DR]

    In S3, Vary is not a user-configurable header. While S3 can deliver CORS headers, CloudFront does not have explicit support for it.

    If your end-goal is to deliver CORS-enables content from CloudFront using S3 as your source, I ended up working around the issue by deploying an app that sits between S3 and CloudFront, which proxies the requests and always adds the correct CORS headers to S3's response so that CloudFront caches the correct data.

    Pros:

    Cons: