Amazon S3/CloudFront redirect www to non-www and HTTP to HTTPS

This article assumes you want to redirect a www version of a domain (e.g. www.example.com) to the non-www root domain (e.g. example.com) with HTTPS, and using Amazon S3 static site redirect and CloudFront.

Introduction

Before we start, there are a few important notes to keep in mind:

  • In order to redirect via CloudFront we will have to configure an Amazon S3 bucket for redirect.
  • If you are already using an Amazon S3 bucket for redirect and you want to enable the HTTPS redirect, then you need to use Amazon CloudFront. It's not possible to use HTTPS on Amazon S3 with a custom domain.
  • If you want the origin domain to redirect via HTTPS, then you MUST have a valid SSL/TLS certificate that covers that domain. You can use Amazon Certificate Manager to request a new certificate free of charge, or use an existing certificate if you already have one.
  • If you want to redirect the root domain to www, then you must use a DNS hosting provider such as DNSimple that supports CNAME-like features for the root domain. You will need to point the root domain to the Amazon CloudFront distribution endpoint, and you can't use a CNAME. At DNSimple we call it the ALIAS record.
  • The redirect target doesn't have to be hosted on Amazon S3 or Amazon CloudFront. For example, you can deploy your site example.com on Heroku, and use Amazon S3+CloudFront to redirect www.example.com to example.com.

CloudFront Configuration

To configure the redirect, follow the detailed instructions in this article. In the referenced article, the redirecting host name is the host name that will redirect, whereas the target host name is the target of the redirect.

For example, if you want to redirect http://www.example.com and https://www.example.com to https://example.com, then you will have to follow the steps detailed in the article and:

  • create a bucket called www.example.com, and setup the redirect to https://example.com
  • request or import a certificate for www.example.com
  • configure a distribution for www.example.com
  • create a CNAME DNS record to point www.example.com to the Amazon CloudFront distribution endpoint

Instead, if you want to redirect http://example.com and https://example.com to https://www.example.com, then you will have to follow the steps detailed in the article and:

  • create a bucket called example.com, and setup the redirect to https://www.example.com
  • request or import a certificate for example.com
  • configure a distribution for example.com
  • create an ALIAS record to point example.com to the Amazon CloudFront distribution endpoint

If you should experience some issues, check the common errors section.