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
Step 2
Step 3
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 www.jamesmiller.blog if (request.headers.host[0].value === 'www.jamesmiller.blog') { // return the new set of headers containing the redirect return { status: '301', statusDescription: `Redirecting to apex domain`, headers: { location: [{ key: 'Location', value: `https://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" } ] }