At a certain point it may be desirable to redirect traffic on your static site. One example is redirecting HTTP traffic to an HTTPS endpoint once you have SSL/TSL configured. Another would be redirecting traffic going to your naked domain (like foo.bar) to a domain starting with www (www.foo.bar), or vice versa.
This document presents a high level explanation of how to configure AWS CloudFront and S3 Hosted Websites to redirect requests from HTTP to HTTPS endpoints, and from one domain to another.
Details
The following sections assumes that you have prior knowledge in configuring, and have already setup:
- an S3 Hosted Website.
- a CloudFront distribution.
- Route 53 zones and configured DNS records.
There's a wealth of information out there on how to do all the above. No sense in repeating it here.
Redirecting HTTP requests to HTTPS
HTTP to HTTPS redirection can, and should, be handled by CloudFront irrespective of the origin.
Here is a sequence diagram outlining how HTTP to HTTPS redirection operates under CloudFront.
This is configured via the CloudFront console under Behaviors, setting the Viewer Protocol Policy to Redirect HTTP to HTTPS. For details on how to accomplish this, read the Requiring HTTPS for Communication Between Viewers and CloudFront AWS documentation.
Redirecting to a different domain
CloudFront relies on the origin to manage all other forms of redirects. Turns out that S3 Hosted Websites supports a few different forms of redirection. In this particular instance we are interested in redirecting all traffic from one domain to another one.
Let us say we wanted to redirect all traffic going to the foo.bar domain to an already existing www.foo.bar site (redirect from the naked domain to the www domain). We would have to set up a second CloudFront and S3 Hosted Website configuration for foo.bar.
The following sequence diagram illustrates how this would function with a CloudFront distribution backed by an S3 Hosted Website and assumes that both www.foo.bar and foo.bar have been configured as described in the Redirecting HTTP requests to HTTPS section above.
Setting up an S3 Website to redirect traffic to another domain is pretty straightforward and covered in the How Do I Redirect Requests to an S3 Bucket Hosted Website to Another Host AWS documentation.
Note that in the sequence diagram above the foo.bar S3 Website is configured to return an HTTPS version of the URL. This is to avoid a second round of redirection, from HTTP to HTTPS, when the browser gets to the www.foo.bar site. I only did this for demonstration purposes. You can modify it which ever way you would like.
The same could be achieved with CloudFront and any web server as the origin (like Nginx, Apache, or others) instead of S3 Website, but if going serverless is the end goal, the CloudFront and S3 Website configurations presented in the document are the way to go.