Introduction

 

This guide is on how to do URL rewriting in AWS CloudFront. A feature which is not immediately available, but which is possible to implement with a Lambda function.

 

user_76457_5993ef7f7f0c2.png_800.jpg

Getting Started

 

First of all, you need a CloudFront (CF) distribution. I’m not going to walk you through on how to set-up a CF distribution here and i’ll assume that if you need to do URL rewriting in CF you already have one.

 

We are going to create a simple Lambda Function whose job is to change the request URI, therefore re-mapping the original request to a new destination.

 

Please note that when coding a Lambda for CF, only the NodeJs environment is available. Anyway in this case the Lambda is so simple you don’t need to be familiar with neither Javascript or NodeJS.

 

I’m going to show the code first and then i’ll share a few tips.

 

exports.handler = (event, context, callback) => {
 // this is the request we want to re-map
 var request = event.Records[0].cf.request;

// the request has a ‘uri’ property which is the value we want to overwrite
// rewrite the url applying your custom logic
request.uri = ‘some custom logic here to rewrite the url’;

// quit the lambda and let the request chain continue
callback( null, request );
};

 

Allright, but how do you know there’s a ‘event.Records[0].cf.request’ at all?

It’s a mistery reasearchers around the globe are still investigating.

To cope with the lack of documentation, the best way i found is to create a lambda and then look at the samples in the Test page.

The screenshot below will clarify any doubts:

xmjnbhnZMcYK.png

What if there’s no sample that fits my use-case?

Well, in this case you will have to debug the old way by adding a log statement in your lambda. For example in a NodeJS lambda you can use console.log. To know which logging api is available to the language you are using please consult the Programming Model section of the docs and then find the Logging sub-section.

 

Sources / Resources

For more information on Lambdas, please see here.

For the particular flavour of lambdas discussed in this guide also see the docs for Lambda Edge.

 

Comments are disabled for this guide.