Skip to content

Instantly share code, notes, and snippets.

@vgorloff
Last active August 29, 2021 14:11
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 vgorloff/d82afd476f04dd06c2339d8661ef5bf4 to your computer and use it in GitHub Desktop.
Save vgorloff/d82afd476f04dd06c2339d8661ef5bf4 to your computer and use it in GitHub Desktop.
Example how to redirect client to new location with AWS CloudFront Function. E.g. when you deleted NextJS page, but still want to redirect clients (Native app or Search index) to new location.
// NOTE: Choose "viewer request" for event trigger when you associate this function with CloudFront distribution.
/** See also:
- JS Specs: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/functions-javascript-runtime-features.html
- The request Specs: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/functions-event-structure.html
*/
function makeRedirectResponse(location) {
var response = {
statusCode: 301,
statusDescription: 'Moved Permanently',
headers: {
'location': { value: location }
}
};
return response;
}
function handler(event) {
var mappings = [
{ from: "/products/decode/app.html", to: '/products/decode.html' },
{ from: "/products/decode/privacy/2021_01_25.html", to: '/products/decode/privacy.html' }
];
var request = event.request;
var uri = request.uri;
for (var i = 0; i < mappings.length; i++) {
var mapping = mappings[i]
if (mapping.from === uri) {
return makeRedirectResponse(mapping.to)
}
}
return request;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment