Created
February 5, 2019 14:09
-
-
Save a-h/76c9d5001d5c713488686090b396b707 to your computer and use it in GitHub Desktop.
Lambda@Edge to carry out redirects and apply default documents (index.html) to incoming requests
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
var path = require('path'); | |
const redirects = { | |
"/about-us": { to: "/about", statusCode: 301 }, | |
"/contact-us/head-office": { to: "/contact/head-office", statusCode: 302 }, | |
}; | |
exports.handler = async event => { | |
const { request } = event.Records[0].cf; | |
const normalisedUri = normalise(request.uri); | |
const redirect = redirects[normalisedUri]; | |
if (redirect) { | |
return redirectTo(redirect.to, redirect.statusCode); | |
} | |
if (!hasExtension(request.uri)) { | |
request.uri = trimSlash(request.uri) + "/index.html"; | |
} | |
return request; | |
}; | |
const trimSlash = uri => hasTrailingSlash(uri) ? uri.slice(0, -1) : uri; | |
const normalise = uri => trimSlash(uri).toLowerCase(); | |
const hasExtension = uri => path.extname(uri) !== ''; | |
const hasTrailingSlash = uri => uri.endsWith('/'); | |
const redirectTo = (to, statusCode) => ({ | |
status: statusCode.toString(), | |
statusDescription: 'Found', | |
headers: { | |
location: [{ | |
key: 'Location', | |
value: to, | |
}], | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment