Redirect Your Website From Non-WWW to WWW URL Using AWS S3 + CloudFront + Route 53

I am a lazy person. I never type www in front of any URL 😆 For example, when I want to Google something, I just type google.com instead of www.google.com.

Not surprisingly, a lot of people are like me. We don’t like typing those extra 3 letters. Fortunately, most companies respect our laziness and have found a way to successfully redirect us to their websites even without explicitly typing www.

So how is this achieved 🤔

Goal

Setup

S3

  • Bucket name should be the non-www version of your URL.

Step 2: enable static website hosting.

  • For hosting type, select “Redirect requests for an object”.
  • For host name, type the www version of your URL.

Step 3: edit bucket policy.

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicRead",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::example.com/*"
}
]
}

CloudFront

  • For origin domain, please do NOT select any option from the auto-populated dropdown, because those options are in S3 REST API format. However, in our use case, we want website endpoints. We need to type it manually here.
  • For view protocol policy, select “Redirect HTTP to HTTPS”.
  • For alternative domain name (CNAME), type the non-www version of your URL.
  • For custom SSL certificate, select the certificate associated with this domain.

Route 53

  • For record name, just leave it empty.
  • For record type, select A.
  • For route traffic to, toggle “Alias” first. Then you should see the input box become a dropdown. Select “Alias to CloudFront distribution” option. Lastly, in the distribution dropdown (there should be only one), select the CloudFront distribution URL associated with this domain.

Conclusion

I aim to save people from the overwhelming tsunami of information.