Categories
Posts

Serving your Django app’s static & media files with S3 and CloudFront (super fast & easy!)

The following steps will leave you with an AWS setup for serving your app’s files via xyz123.cloudfront.net URLs:

  1. Create an S3 bucket (e.g. my-app-bucket-staging) and leave all settings at their defaults
  2. Open the newly created bucket and navigate to Permissions → CORS configuration
  3. Create an XML CORSConfiguration that defines from which domain the contents of your bucket should be accessible:
<CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>https://www.example.com</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
    </CORSRule>
</CORSConfiguration>
It’s also possible to grant access via any domain by specifying <AllowedOrigin>*</AllowedOrigin>, but be sure to understand the possible consequences
  1. Use the aws CLI to upload the files in your STATIC_ROOT to the newly created bucket:
aws s3 cp --recursive static/_root/ s3://my-app-bucket-staging/static/
  1. Do the same for any media files your app might already have:
aws s3 cp --recursive media/ s3://my-app-bucket-staging/media/
  1. Open CloudFront and choose to create a web distribution
  2. Choose the newly created S3 bucket as your distribution’s Origin Domain Name
  3. Optionally, activate Restrict Bucket Access to prevent users from directly accessing your Amazon S3 URLs
  4. Activate Create a New Identity and set its name in the Comment field (e.g. access-identity-my-app-bucket-staging.s3.amazonaws.com)
  5. Choose Yes, Update Bucket Policy to automatically grant read permission to the origin access identity so that CloudFront can actually access objects in the S3 bucket
  6. Optionally, set Viewer Protocol Policy to Redirect HTTP to HTTPS or HTTPS Only (recommended)
  7. Set Allowed HTTP Methods to GET, HEAD, OPTIONS and add OPTIONS to Cached HTTP Methods to allow for preflighted requests
  8. As shown in the below screenshot, add the three required headers to Whitelist Headers in order to implement CORS in CloudFront
These settings make it possible to reference xyz123.cloudfront.net URLs in the context of a custom domain
  1. Enable Object Caching by activating the Customize option to have CloudFront deal with object caching. The default TTL (time to live) values are appropriate for most cases
  2. Optionally, activate the Compress Objects Automatically option to take advantage of CloudFront’s built-in compression capabilities (recommended)
  3. Set a Price Class according to your requirements and finally click the Create distribution button
  4. If necessary, create another CloudFront distribution for your media files with the same settings as above except Origin Path set to /media
  5. Be sure to grab a beverage of your liking before trying to access your files via the xyz123.cloudfront.net URL as it can take a while for S3 to distribute everything in the background