CloudFront + S3 + Lambda@Edge implement 301 redirect step by step
Requirement
Nowadays, developers tend to host their website on third-party services such as Heroku, Vercel, etc.
The problem is we want to set both the root domain and www
as our URL. Unfortunately, a number of popular DNS hosts such as GoDaddy, Route53, and others do not support ANAME
types of records. So we have to find a solution to implement URL redirects/forwarding.
It means finally we will get a result like if users visit https://a.com
it redirects to https://www.a.com
or the URL you want.
Phil Frep provides explain in detail why using Lambda@Edge is a good option in Using Lambda@Edge to setup server-side redirects on a Cloudfront+S3 static site. In this post, We will go through set up step by step.
Using Lambda@Edge solution
Create a Certificate
First, create a certificate of your domain, for example, I have a domain — andyyou.dev
I want andyyou.dev
redirect to andyyou.github.io
In this step, please make sure the certificate is created on region us-east-1
. Because of CloudFront can only use the certificate store on N. Virginia
Visit AWS Certificate Manager Console, click Provision certificates
→ Get started
Enter your domain which will is users' input. The URL will redirect the destination URL. In this example is andyyou.dev
You can select the way you prefer for validation
If you are using Route53 to manage your DNS you can click the bottom-left button to create a record.
Finally, we got a certificate.
Create S3 Bucket
Enter your Bucket name
and keep the rest of the options as default. By the way, the region here is up to you.
Create CloudFront Distribution
In Origin Domain Name
select your S3 bucket we just created. It worth to note we will select Yes, Update Bucket Policy
which allows CloudFront to access our S3.
Because we want to use our own domain to access CloudFront so we have to set up Alternate Domain Names
. We create a certificate because we want to support SSL for the domain.
Setup Route53 or Your DNS
Create an A record as alias then select our CloudFront
Create Lambda@Edge
Visit AWS Lambda Console
Enter the Function name
and Runtime
you want. We will use Nodejs in this post. You can check the code as follows to make decision
The most important step is you should add Basic Lambda@Edge permissions to the role.
Modify the codebase, this is a very simple example you can modify by yourself.
Save, then Deploy to Lambda@Edge
Please make sure the Distribution
is that you want(Setup above) and Origin response
event.
Click Deploy
and we finish. Wait for CloudFront update for few minutes we can redirect our domain to another through Lambda@Edge.