Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrsweaters/4333b6a609a72b6edd40fe805f71cba0 to your computer and use it in GitHub Desktop.
Save mrsweaters/4333b6a609a72b6edd40fe805f71cba0 to your computer and use it in GitHub Desktop.
Redirect to trailing slashes on CloudFront with AWS Lambda. (all this because S3 uses 302 redirects instead of 301)
'use strict';
const path = require('path')
exports.handler = (event, context, callback) => {
//get request object
const { request } = event.Records[0].cf
const url = request.uri;
//we need to determine if this request has an extension.
const extension = path.extname(url);
//path.extname returns an empty string when there's no extension.
//if there is an extension on this request, continue without doing anything!
if(extension && extension.length > 0){
return callback(null, request);
}
//there is no extension, so that means we want to add a trailing slash to the url.
//let's check if the last character is a slash.
const last_character = url.slice(-1);
//if there is already a trailing slash, return.
if(last_character === "/"){
return callback(null, request);
}
//add a trailing slash.
const new_url = `${url}/`;
//debug.
console.log(`Rewriting ${url} to ${new_url}...`);
//create HTTP redirect...
const redirect = {
status: '301',
statusDescription: 'Moved Permanently',
headers: {
location: [{
key: 'Location',
value: new_url,
}],
},
};
return callback(null, redirect);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment