Lambda@Edge Function Standard Redirects for Cloudfront

JS
S
JavaScript

Function to redirect (302) origins to a different URL. This function CloudFront trigger needs to be set with: Event type: origin-requestPath pattern: * By: https://github.com/digital-sailors/standard-redirects-for-cloudfront/blob/master/index.js

1exports.handler = (event, context, callback) => {
2  const request = event.Records[0].cf.request;
3  
4  let prefixPath; // needed for 2nd condition
5
6  if (request.uri.match('.+/$')) {
7    request.uri += 'index.html';
8    callback(null, request);
9  } else if (prefixPath = request.uri.match('(.+)/index.html')) {
10    const response = {
11      status: '301',
12      statusDescription: 'Found',
13      headers: {
14        location: [{
15          key: 'Location', value: prefixPath[1] + '/',
16        }],
17      }
18    };
19    callback(null, response);
20  } else if (request.uri.match('/[^/.]+$')) {
21    const response = {
22      status: '301',
23      statusDescription: 'Found',
24      headers: {
25        location: [{
26          key: 'Location', value: request.uri + '/',
27        }],
28      }
29    };
30    callback(null, response);
31  } else {
32    callback(null, request);
33  }
34}

Created on 6/19/2018