Lambda function 301 redirects

Lambda function 301 redirects

Redirect traffic from the www subdomain to the root domain. ...

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

Lambda function 301 redirects
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

Lambda function 301 redirects
Attach the lambda@edge access policy (see code below) to that lambda function, then click the ‘Deploy to Lambda@Edge’ using the actions button and ensure it is attached to the right CDN with the options ‘Origin Request’ selected.

Step 3

Lambda function 301 redirects
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 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"
    }
  ]
}

Share this post