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

Zico Deng
3 min readSep 3, 2021

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

This post will guide you to set up non-www to www URL redirection for your website using AWS S3, CloudFront, and Route 53. As an example, I will be setting up example.com to www.example.com redirection.

Setup

S3

Step 1: create a new S3 bucket.

  • 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

Step 1: create a new CloudFront distribution.

  • 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

Step 1: create a new type A record.

  • 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

Thatā€™s it! You are only a few steps away to keep your website viewers lazy šŸ¤£

--

--