user366810
user366810

Reputation: 424

LambdaExecutionError from AWS CloudFront When Trying to do 301 Redirect with Lambda Function

I’m trying to set up redirects on CloudFront using Lambda@Edge but I keep getting a vague error. Here’s my setup.

When I click “Deploy to Lambda@Edge”,

When I curl a URL,

Any idea what might be causing the error?

export const handler = async (event, context) => {
    const { request, response } = event.Records[0].cf;

    var newLocation = "";
    var statusCode = 301;
    var statusDescription = "Moved Permanently";
    
    console.log(request);
    
    switch(request.uri) {
        case '/file1.pdf':
            newLocation = '/file2.pdf';
            statusCode = 301;
            break;
        case '/file3.pdf':
            newLocation = '/file4.pdf';
            statusCode = 301;
            break;
    }
    
    if (statusCode === 302) {
        statusDescription = "Found";
    }
    
    if (newLocation !== "") {
        response.headers['location'] = [
          {
            key: 'Location',
            value: newLocation,
          },
        ];
        
        return {
          status: statusCode,
          statusDescription: statusDescription,
          headers: response.headers,
        };
    } else {
        return response;
    }
};

Upvotes: 1

Views: 713

Answers (1)

Cristian
Cristian

Reputation: 1694

I know you asked about Lambda@Edge, but have you considered implementing your redirect using CloudFront Functions? It's faster, cheaper, and a easier to configure in the Functions section of the CloudFront console. You can also test it out with different request URIs before deploying to ensure it's working.

Here's an example to get you going, you'll just need to update it slightly to match your use case - https://github.com/aws-samples/amazon-cloudfront-functions/tree/main/redirect-based-on-country

Upvotes: 0

Related Questions