Kit Cross

Quick 301 redirects with Lambda@Edge and Cloudfront

Lambda functions allows easy permanent redirects on Cloudfront

Recently I needed to move some blog posts from one domain to another.

There’s one easy option:

<meta http-equiv="refresh" content="0;url=https://url.com">

This is a client side redirect. But with Cloudfront you can use server side redirects and preserve any SEO credibility you’ve built up. They’re also faster.

The key is to use Lambda@Edge. We’ll create a new function using the Node.js 12.x runtime.

'use strict';

exports.handler = (event, context, callback) => {
    const request = event.Records[0].cf.request;
    const uri = request.uri;

    if (uri == "/old-article-url/") {
        const response = {
            status: '301',
            statusDescription: 'Permanently Moved',
            headers: {
                location: [{
                    key: 'Location',
                    value: 'https://new-article-url/'
                }]
        }}
        callback(null, response);
    } else {
        callback(null, request)
    }
};

To activate this function:

  • save it and publish a new version
  • copy the ARN of this published function
  • edit the behaviors of your Cloudfront distribution
  • add this as a viewer request function

This doesn’t scale well to hundreds of URLs – there are much more complicated methods that pull JSON listings from S3 buckets. But it’s perfect for quick redirects to tell Google about a change of address.

Found this useful? Any questions or comments, let me know on Twitter.

web server javascript