Created
July 24, 2024 22:22
-
-
Save nickhudkins/e94298e18f1f64d2a22bc1e640715db9 to your computer and use it in GitHub Desktop.
Trailing Slash CloudFrontFunction
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
function handler(event) { | |
const request = event.request; | |
const uri = request.uri; | |
const parts = uri.split("/"); | |
const lastPart = parts[parts.length - 1]; | |
const isAssetRequest = lastPart.includes("."); | |
const isDirectoryRequest = uri.endsWith("/"); | |
const needsTrailingSlash = !isAssetRequest && !isDirectoryRequest; | |
if (needsTrailingSlash) { | |
const host = request.headers.host.value; | |
const newURL = `https://${host}${request.uri}/`; | |
return { | |
statusCode: 302, | |
statusDescription: "Found", | |
headers: { location: { value: newURL } }, | |
}; | |
} else if (isDirectoryRequest) { | |
return Object.assign(request, { uri: `${request.uri}/index.html` }); | |
} | |
return request; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's useful