Skip to content

Instantly share code, notes, and snippets.

@nickhudkins
Created July 24, 2024 22:22
Show Gist options
  • Save nickhudkins/e94298e18f1f64d2a22bc1e640715db9 to your computer and use it in GitHub Desktop.
Save nickhudkins/e94298e18f1f64d2a22bc1e640715db9 to your computer and use it in GitHub Desktop.
Trailing Slash CloudFrontFunction
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;
}
@nickhudkins
Copy link
Author

It's useful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment