Using Lambda@Edge For Cloudfront Redirects

Masterful URL Rewriting: Dynamic Redirections with Lambda@Edge

Let us make things easier!

Enhancing The Cloudfront Experience

Lambda@Edge is a service provided by AWS that allows you to run custom code in response to CloudFront events. CloudFront is AWS's content delivery network (CDN) service that helps distribute content (e.g., web pages, images, videos) to users from edge locations around the world. Lambda@Edge allows you to execute AWS Lambda functions at these edge locations, which are closer to the end users, to customize and enhance the behavior of your CloudFront distribution.

One common use case for Lambda@Edge is URL rewriting, where you can modify the URLs of incoming requests before they are processed by your CloudFront distribution. Here's how you can achieve URL rewriting using Lambda@Edge:

  1. Create an AWS Lambda Function: First, you need to create an AWS Lambda function that will handle the URL rewriting logic. This function can be written in Node.js, Python, or other supported languages.
  2. Associate Lambda Function with CloudFront Distribution: Next, you associate this Lambda function with your CloudFront distribution by creating a CloudFront Trigger. You can specify when the Lambda function should execute, such as during the viewer request, origin request, etc.
  3. Write URL Rewriting Logic: In your Lambda function code, you can access the incoming request's URL and modify it according to your requirements. For example, you can add query parameters, remove parts of the URL, or even perform more complex transformations.
  4. Return the Modified Request: After you've made the necessary modifications to the request URL, you return the modified request to CloudFront. CloudFront will then use this modified request to fetch the content from your origin server or cache.
  5. Test and Deploy: Ensure that your Lambda function is tested thoroughly, and then deploy it to the associated CloudFront distribution.
exports.handler = async (event) => {
    const request = event.Records[0].cf.request;
    const modifiedUri = `${request.uri}?customParam=123`;
    request.uri = modifiedUri;
    return request;

Keep in mind that Lambda@Edge functions should be designed to be lightweight and performant, as they execute at the edge locations, and latency is a crucial factor.

Let's look at a recent use case I had when one of our partners changed all of their filenames in s3.  Since s3 only allows for changing of prefixes, I needed to use Lambda@Edge to redirect from the old filenames to the new ones.  Here is a look at the code used: 

const AWS = require('aws-sdk');
const fs = require('fs'); // Node.js file system module

// Read the file mappings from the JSON file
const fileMappings = JSON.parse(fs.readFileSync('file-mappings.json', 'utf8'));

exports.handler = async (event) => {
    const request = event.Records[0].cf.request;
    const requestUri = request.uri;

    // Check if the request URI exists in the fileMappings
    if (fileMappings.hasOwnProperty(requestUri)) {
        // Get the new filename from the mappings
        const newFileName = fileMappings[requestUri];

        // Modify the request to point to the new filename
        request.uri = request.uri.replace(requestUri, newFileName);

    return request;

In this Lambda function, we first read the file mappings from the file-mappings.json file. Then, we check if the requested URI exists in the JSON object. If it does, we replace the old filename with the corresponding new filename from the mappings.

Ensure that you have the file-mappings.json file in the same directory as your Lambda function code. This file should contain the mapping of old filenames to new filenames as shown in the example above.

Here is an example of how I have my file-mappings.json structured:

    "old-file-1.jpg": "new-file-1.jpg",
    "old-file-2.jpg": "new-file-2.jpg",
    "old-file-3.jpg": "new-file-3.jpg"

With this setup, whenever a user accesses a URL with an old filename, the Lambda@Edge function will look up the mapping in the JSON file and redirect the request to the new filename, allowing us to manage the redirections more dynamically.

In conclusion, Lambda@Edge and CloudFront provide a powerful combination of services for customizing and optimizing content delivery on AWS. By leveraging Lambda@Edge, you can dynamically rewrite CloudFront URLs to meet your specific requirements, whether it's for URL redirection, content transformation, or other use cases. Additionally, the ability to store filename mappings in a JSON file adds flexibility and ease of management when updating redirection rules. This approach not only enhances user experience but also allows for seamless transitions in content organization, making it a valuable tool for developers and businesses looking to provide a more tailored and efficient web experience to their audience.

Continue reading.

Extending Craft's Element API with Custom Serializers

The Element API plugin is a very powerful tool that you can use for quickly exposing your data structures to an external source.

Find out more
Why We Love Craft CMS

Here at Brilliance, we LOVE CraftCMS. Our clients love it as well.

Find out more
Ethereum Development Community Nears Merge Date for Proof of Stake

A brief introduction to consensus mechanisms and why proof of stake is the right move for Ethereum.

Find out more
See all posts

Let's chat about your project

6118 SE Belmont St Ste 404
Portland, OR 97215

This site is protected by reCaptcha and its Privacy Policy and Terms of Service apply.

Contact image