Skip to content

Instantly share code, notes, and snippets.

@jeanlescure
Last active August 28, 2021 20:10
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 jeanlescure/1aa476cc88605edd2a5badee82fa6d22 to your computer and use it in GitHub Desktop.
Save jeanlescure/1aa476cc88605edd2a5badee82fa6d22 to your computer and use it in GitHub Desktop.
aws s3 api gateway cloudfront lambda@edge function which fixes subdirectory in static website hosting by redirecting "**/" to "**/index.html"
// BASIC
'use strict';
exports.handler = (event, context, callback) => {
// Extract the request from the CloudFront event
const {request} = event.Records[0].cf;
// Extract the URI from the request
const {uri} = request;
// Return to CloudFront
return callback(
// No error
null,
// Modify a clone of the request object using spread operation
{
...request,
// Override uri, atch any '/' that occurs at the end of a URI. Replace it with a default index
uri: uri.replace(/\/$/, '\/index.html'),
}
);
};
// WITH WWW AND LANGUAGE REDIRECT LOGIC
'use strict';
exports.handler = (event, context, callback) => {
// Extract the request from the CloudFront event
const {request} = event.Records[0].cf;
// Extract the URI from the request
const {origin, uri, headers} = request;
// If domain has'www', redirect to base domain, without 'www'
if ((/^www\./).test(((origin || {}).custom || {}).domainName)) {
const fixedDomain = origin.custom.domainName.replace(/^www\./, '');
return callback(
// No error
null,
{
status: '301',
statusDescription: 'Moved Permanently',
headers: {
'location': [{
key: 'Location',
value: `https://${fixedDomain}${uri}`,
}],
'cache-control': [{
key: 'Cache-Control',
value: "max-age=3600"
}],
},
},
);
}
let response;
if(request.uri == '/') {
// for proper SEO, if request is for root, redirect to appropriate language
response = {
status: '301',
statusDescription: 'Moved Permanently',
headers: {
'location': [{
key: 'Location',
value: '/en/',
}],
'cache-control': [{
key: 'Cache-Control',
value: "max-age=3600"
}],
},
};
if (typeof headers['accept-language'] !== 'undefined') {
const supportedLanguages = (headers['accept-language'][0] || {}).value || '';
if(supportedLanguages.startsWith('es')){
response.headers.location[0].value = '/es/';
}
}
} else {
// Modify a clone of the request object using spread operation
response = {
...request,
// Override uri, atch any '/' that occurs at the end of a URI. Replace it with a default index
uri: uri.replace(/\/$/, '\/index.html'),
}
}
// Return to CloudFront
return callback(
// No error
null,
response,
);
};
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"edgelambda.amazonaws.com",
"lambda.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment