Redirect www to non www AWS route53 with S3 and cloudfront

I have created a playlist on youtube on which i have shown how to upload a django website on AWS EC2 server, and how to connect to a domain using Route53. In that series I have used an elastic load balancer to redirect http to https. Now We will see how we can leverage cloudfront to redirect www to non www In this tutorial we will see how we can redirect www to non www. Currently you can see if you have both www and non www url indexed in google.

Google index both www and non www version which is not good for seo

To do that we will use two AWS services S3 and cloudfront.

What is cloudfront.

AWS CloudFront is a global content delivery network (CDN) service that accelerates delivery of your websites, APIs, video content, or other web assets. It integrates with other Amazon Web Services products to give developers and businesses an easy way to accelerate content to end users with no minimum usage commitments.

What is S3 A

AWS S3 is a storage service that allows you to store and retrieve data from anywhere on the web.

Let start with S3

Create an S3 bucket to redirect www to nonwww

Create S3 bucket for redirecting www to non www

Create s3 bucket to redirect www to non www

 

make acess public for S3 bucket for redirecting www to non www

Now click on create bucket. When bucket is completed, now go to properties, and down the bottom, enable the redirect and do following settings. Remember your host name should be with www. If you are planing to redirect non www to www.

enable static web hosting and allow redirect for redirecting www to non www

Click on save changes and you can see a url below. Copy this url without http

Settings on CloudFront to redirect www to nonwww

Go to cloudfront, create distribution

Enter your copied url without http in origin domain as follow

Create cloudfront distribution to redirect www to non www

In default cache behavior, make the following settings. The only change made is in viewer protocol

Create cloudfront distribution to redirect www to non www

 

Now in settings tabs, choose ssl certificate and add alternative domain. ALternative domains are very important without this you cant see it in route53.

Alternative domain and ssl for redirecting www to non www

 

Click on create distribution at the end, and it will take you some time to create it.

Changes in route53

Now to go to route53 and currently my route53 look like

My settings in route53

I removed the CNAME, add a new A record, point it to the cloudfront distribution i created earlier by turning alias on

How to add cloudfront distribution to route53

This is how we can redirect www to non www using AWS route53, S3 and cloudfront