Skip to content

Instantly share code, notes, and snippets.

@ultim8k
Last active December 9, 2018 17:18
Show Gist options
  • Save ultim8k/a2a399ac875943dd72b0b8e2b4290f7a to your computer and use it in GitHub Desktop.
Save ultim8k/a2a399ac875943dd72b0b8e2b4290f7a 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.

@ultim8k
Copy link
Author

ultim8k commented Feb 16, 2018

Also in terraform

You can insert the following in your resource "aws_s3_bucket" ... {...} block

cors_rule {
  allowed_headers = ["*"]
  allowed_methods = ["GET"]
  allowed_origins = ["__PRODUCTION_DOMAIN__", "__LOCAL_DOMAIN__"]
  max_age_seconds = 3000
}

And the following to your resource "aws_cloudfront_distribution" ... {...} block

default_cache_behavior {
  allowed_methods = ["GET", "HEAD", "OPTIONS"]
  cached_methods = ["GET", "HEAD", "OPTIONS"]

  forwarded_values = {
    query_string = "false"

    headers = ["Access-Control-Request-Headers", "Access-Control-Request-Method", "Origin"]
  }
}

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