Last active
August 29, 2021 14:11
-
-
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.
This file contains 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
// 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