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 🤔
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.
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.
- 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.
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.
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.
That’s it! You are only a few steps away to keep your website viewers lazy 🤣