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
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/*"
}
]
}
- Open the bucket policy editor. Copy and paste the above policy.
- If you encounter access denied error when saving changes even as a root user, you can temporarily deselect all block public access options.
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 š¤£