Forked from nabilfreeman/lambda-redirect-to-trailing-slash.js
Created
May 9, 2018 01:13
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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