Static site hosting on AWS S3 and CloudFront

How to get S3 redirection working in ClodFront

Posted on December 15, 2016

WARNING: Please note that this article was published a long time ago. The information contained might be outdated.

AWS has a great guide on how to configure a static site using S3 and CloudFront, but not much is said on how to redirect requests to www domain to non-www. Since I systematically forget how to configure this, I'm posting here some notes, mainly for myself.

The AWS documentation states that you must create two S3 buckets, one for the root domain (without www), one for the subdomain (www). If you use the non-www as the main domain for your site, you must configure the other (with www) to redirect the requests to the non-www domain.

If you don't use CloudFront, once you've updated the root domain and www subdomain configurations to use the S3 endpoints, you're all set. But if you use CloudFront things are a bit different. The AWS documentation, referring to the ClodFront distribution configuration, states this:

Set Alternate Domain Names (CNAMEs) to the root domain and www subdomain; in this tutorial, these are example.com and www.example.com. These values must be set in order to create aliases for the A records that connect the specified domain names to the CloudFront distribution.

What I wrongly understand reading the documentation is that you should create one single CloudFront distribution and set its Alternate Domain Names (CNAMEs) to both example.com and www.example.com. But doing that results in breaking redirection.

To make redirection work with CloudFront you have to use two distinct distributions, one for the root domain, the other for the www subdomain. Each distribution has to be linked to the correct S3 bucket. Specifically, when creating the CloudFront distribution for the subdomain you must:

  • take note of the endpoint of the S3 bucket used for redirecting the requests (should be the one with www)
  • use that endpoint (not the id that AWS lets you choose in the pop-up list) in the Origin Domain Name configuration field
  • leave empty Origin Path
  • leave empty Default Root Object

Another important configuration has to be done on the S3 bucket of the root domain (the non-www one): in the Static Website Hosting section of the bucket properties, you must check Enable website hosting.

With this configuration, when one opens www.example.com, CloudFront follows the redirect configuration of the S3 bucket endpoint used in the Origin Domain Name.