Setup AWS S3 and Cloudfront CDN
Overview
This guide runs through amazon S3 and Cloudfront setup and configuration to utilize for application asset upload (to s3) and CDN delivery (from cloudfront).
NOTE: This guide does not contain any application integration.
Table of Contents
Setup S3
S3 Getting started
If you are new to AWS S3, checkout the S3 Getting Started guide which will take you through:
S3 Settings
Bucket policy
S3 bucket policy enables authentication and authorization using amazons IAM (Identity and Access Management) policies. This allows you, at a granular level, to enforce what accounts can do what actions on what S3 buckets.
Example policy
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::<ACCOUNT_NUMBER>:root"
},
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::test-ladsh"
},
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::<ACCOUNT_NUMBER>:root"
},
"Action": [
"s3:PutObject",
"s3:PutObjectAcl",
"s3:GetObject",
"s3:GetObjectAcl",
"s3:DeleteObject",
"s3:ListMultipartUploadParts",
"s3:AbortMultipartUpload"
],
"Resource": "arn:aws:s3:::test-ladsh/*"
}
]
}
Example visual
CORS configuration
S3 CORS (cross-origin resource sharing) configuration enables rules for S3 to enforce the allowed origin (based on Origin
header), methods, headers, etc. This allowed response information is important and must be forwarded by your CDN provider (shown in cloudfront sections below).
Example configuration
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Example visual
Setup Cloudfront
Cloudfront is Amazon's CDN (content delivery network) offering. Cloudfront hosts servers all around the world to distribute and cache your assets so that you are as close to your users as possible.
Cloudfront Getting Started
If you are new to AWS Cloudfront, checkout the Setting Up and Getting Started guides.
Cloudfront configuration
Origin settings
Cloudfront origin settings point cloudfront to your S3 origin where content is served from and then distributed and cached
Cache behavior settings
Cloudfront cache behavior settings tell cloudfront what and how to cache. Including the origin where assets live and what headers to honor and forward to your users. This is very important to get CORS to work.
Options
- Allowed HTTP methods: GET, HEAD, OPTIONS
- Cache Based on Selected Request Headers: Whitelist
- Whitelist Headers:
- Origin
- Access-Control-Requests-Headers
- Access-Control-Requests-Method
Conclusion
This concludes our simple guide to setup Amazon S3 for asset storage and Amazon Cloudfront for CDN delivery of those assets. I hope you found this useful!