Problem Description
So, ideally you want all the followings to work:
1) https://example.com → https://www.example.com (naked to www)
2) http://www.example.com → https://www.example.com (http to https)
3) http://example.com → https://www.example.com (naked http to www https)
4) https://www.example.com → 🎉 actually show the content as the canonical URL! 🎉
Note that the requirement #3 above can be broken down into two steps, which would be a combination of #1 and then #2.
3B) http://www.example.com → http://www.example.com → https://www.example.com
All these →
s are a HTTP 301 Permanent Redirect.
Requirements
So, you need 3 pieces here:
- A URL Redirect (
example.com → www.example.com
)
- [HTTPS Support] An SSL certificate to cover naked subdomain as well as www (it can be two in one, free in Certification Manager)
- [HTTPS Support] A Protocol Redirect (
http:// → https://
)
Solution
This solution requires many pieces in AWS that should be all free! (or no additional cost)
Step 1) Create a URL Redirect in S3
Create a S3 Static Hosting Website and have it redirect to www.example.com.
Notes:
- Make sure it's publicly accessible.
- Test that the URL works and landing on it actually does the redirect. (or test in terminal via
curl -v
)
- Always test the full URL that contains the region (i.e.
.s3-website-us-west-2.amazonaws.com
)
Step 2) Create an SSL Certificate for naked domain in Certificate Manager
Go to https://us-west-2.console.aws.amazon.com/acm/home?region=us-west-2#/ (change your region to your preferred one) and request a public certificate. Make sure you put both example.com
and www.example.com
there. Verify it in Route 53.
Step 3) Create a Protocol Redirect in CloudFront
Go to CloudFront and create a distribution with Viewer Protocol Policy of "Http => HTTPS redirect" and having its origin be the full URL of the S3 bucket above.
Notes:
- Do NOT point it to S3 directly. Let is point to the full URL of S3 bucket's static website.
- Caching Policy can be No Cache.
- Alternate Domain Names should be your example.com and SSL certification of Step 2 should be fed into it.
- Verify in the "Origins" tab that you are pointing to the S3 full URL path.
Step 4) Have a DNS record in Route53
Finally, go to your route53 DNS record and have it point the naked domain as A
record to the CloudFront distribution of step 3, which should be like d21k2s1234123.cloudfront.net
!
Tada!