Skip to content

Instantly share code, notes, and snippets.

@hemantshekhawat
Forked from ultim8k/aws-static-assets.md
Created June 12, 2018 16:44
Show Gist options
  • Select an option

  • Save hemantshekhawat/311419a2e0d4f9fc6aaebaa03c058cb3 to your computer and use it in GitHub Desktop.

Select an option

Save hemantshekhawat/311419a2e0d4f9fc6aaebaa03c058cb3 to your computer and use it in GitHub Desktop.
Serve assets from AWS S3 + Cloudfront

Serve assets from AWS S3 + Cloudfront

Enabling CORS

S3 bucket setup

Go to your s3 bucket and go to Permissions and then CORS configuration. You can edit and paste the following snippet after replacing __PRODUCTION_DOMAIN__ and __LOCAL_DOMAIN__ with the real domains.

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

Cloudfront setup

Go to your Cloudfront distribution and then go to Behavior tab select the default and edit. Make sure Allowed HTTP Methods are GET, HEAD, OPTIONS and Cached HTTP Methods have OPTIONS checked. Then Cache Based on Selected Request Headers should have whitelist selected. This should enable to edit the Whitelist Headers. Access-Control-Request-Headers, Access-Control-Request-Method, Origin should be all whitelisted. Now an invalidation of the cached files should do the trick. Mind that it may take a few minutes for the cache to expire.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment