Say you want to host some files in an S3 bucket, under your own custom subdomain with nice short HTTPS URLs. For example, you own foo.com
and you want files to be accessible at URLs like https://files.foo.com/bar.txt
.
This is a lot more complex than it should be! It involves configuring 3 separate AWS services and I’m already forgetting the boring details, so let’s write them down for future reference.
Cloud is the future… wait, 3 separate AWS services?
YEP.
…
Creating the S3 bucket
Naming is important here - the S3 bucket must have the same name as the subdomain it will be accessed at. Open up S3 in the AWS console, and:
- Create a new bucket named
files.foo.com
. - Disable “Block all public access”.
- Under the bucket’s Permissions tab, add a bucket policy to make all objects public by default (replace
files.foo.com
with the name of your bucket):
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AddPerm",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::files.foo.com/*"
}
]
}
Certificate Creation+Config
Next up, we need to create a certificate in AWS Certificate Manager.
Hot Tip
Certificates must be created in the
us-east-1
region to work properly with CloudFront. Learn from my mistake, make sure you’re in the right region when performing this step.
- Request a public certificate in Certificate Manager (us-east-1)
- Fully Qualified Domain Name: the subdomain you want (ex:
files.foo.com
) - Use DNS validation
- Fully Qualified Domain Name: the subdomain you want (ex:
- Open up the certificate in CM. It will have “CNAME name” and “CNAME value” fields under Domains, those are used for verification of ownership
- Go to your domain registrar and create a new CNAME that redirects “CNAME name” to “CNAME value”
- note: for some reason AWS puts a
'.'
at the end of each field, strip those off when creating the CNAME
- note: for some reason AWS puts a
- Wait a bit (5 minutes?) until AWS verifies that you own the domain
CloudFront Setup
Finally, you need to set up a CloudFront distribution that uses the certificate to serve content from your S3 bucket.
- Open up CloudFront (in
us-east-1
) and create a new distribution- Origin domain: pick your S3 bucket
- Pick “Redirect HTTP to HTTPS” (optional)
- Add
files.foo.com
to the “Alternate domain name (CNAME)” list - Pick your certificate in “Custom SSL certificate”
- Open the distribution behaviors and set cache policy = CachingDisabled (optional)
- Without this, CloudFront will cache files and serve stale ones for a while. Probably not what you want
- Get the “Distribution domain name” from the CloudFront distribution page
- Go to your domain name registrar and create a new CNAME redirecting
foo.bar.com
to the CloudFront distribution domain name. - Wait a bit for DNS and the CloudFront distribution to catch up, and… you’re (hopefully) done! 🤞