Lambda function 301 redirects
Redirect traffic from the www subdomain to the root domain
Posted in Tidbit
Lambda function 301 redirects
- James Miller
- posted on May 3, 2020May 3, 2020
- No Comment
Using lambda function 301 redirects from a www subdomain to the root domain is common practice , in this post I’ll show how this is done with Lambda functions in a serverless architecture.
Step 1
Create a cloudfront CDN that is linked to any S3 bucket (it doesn’t matter as the contents of that bucket will never get accessed) and create a lambda function in N. Virginia with the below code (be sure to adjust the domain name to the appropriate target).
Step 2
Attach the [email protected] access policy (see code below) to that lambda function, then click the ‘Deploy to [email protected]’ using the actions button and ensure it is attached to the right CDN with the options ‘Origin Request’ selected.
Step 3
Try accessing the www sub domain of your chosen url and you will be redirected to the root domain version of your site. The full url will be copied from the original request, just without the “www.”.
I’ve posted this scripts below (with comments) so you can now use lambda function 301 redirects. I’ve also written a similar post to this on how to solve an obsure rooting issue with cloudfront, that you may find helpful! Enjoy! 😀
Lambda function
exports.handler = async (event) => { // get the request const request = event.Records[0].cf.request;
// if the headers of that address contain jamesmiller.blog if (request.headers.host[0].value === 'jamesmiller.blog') { // return the new set of headers containing the redirect return { status: '301', statusDescription: `Redirecting to apex domain`, headers: { location: [{ key: 'Location', value: `jamesmiller.blog${request.uri}` }] } }; }
return request; };
Lambda permission role’s trust relationship
{
"Version": "2012-10-17",
"Statement": \[
{
"Effect": "Allow",
"Principal": {
"Service": \[
"lambda.amazonaws.com",
"edgelambda.amazonaws.com"
\]
},
"Action": "sts:AssumeRole"
}
\]
}
Snr Software Designer at D-Ford HCD lab.
Lover of Affogatos, Spurs and Super Smash Bros.
#aws #lambda #javascript