Quantcast
Channel: Daniel X Moore – X Blogs the Spot
Viewing all articles
Browse latest Browse all 14

AWS CloudFront + S3 + Allow all CORS

$
0
0

If you’ve ever set up CloudFront with CORS you know that it can be a little tricky to get right. In fact, the configuration AWS recommends makes it incredibly difficult to take full advantage of the CloudFront caching while still honoring CORS.

If you have some specific set of allowed origins with different CORS rules, then forwarding the Origin header makes sense, but what about the case where you simply want to allow CORS for all origins? If you forward the Origin header it reduces the abilit to cache the response. If you want to support Simple Requests to skip the OPTIONS request AWS may not even return the proper CORS headers at all. I’ve even seen cases where if a GET request was made to a URL (like an image) without CORS then CloudFront would cache the non-CORS version of that resource, even if later requests added the Origin header. Of course this probably means I didn’t set up my CloudFront caching “exactly just right”, but why make things complicated?

Here’s one weird trick to set up CloudFront to allow all origins and cache aggressively, even on simple requests. Explicitly set the Origin custom header in the CloudFront distribution.

Origin https://www.example.com

That’s it. Now every response will always have the CORS headers because when CloudFront forwards the request to S3 it includes the Origin header. Even on simple requests. You can probably put in any origin domain you want, but www.example.com is just what I used.


Viewing all articles
Browse latest Browse all 14

Latest Images

Trending Articles





Latest Images