scar
scar copied to clipboard
Suggestion: Replace second bucket and CloudFront distribution with Lambda function
A Lambda@Edge deployment would, I think, be a more lightweight solution for redirection than another bucket and distribution.
Something like (written for !Sub
):
exports.handler = async (event, context) => {
const request = event.Records[0].cf.request;
const headers = request.headers;
const host = headers.host[0].value.toLowerCase();
if (host == 'www.${APEX_DOMAIN}') {
/*
* Generate HTTP redirect response with 302 status code and Location header.
*/
const response = {
status: '302',
statusDescription: 'Found',
headers: {
location: [{
key: 'Location',
value: 'https://${APEX_DOMAIN}',
}],
},
};
return response;
} else {
return request;
}
};
How about the cost of this at scale? The current S3 option would be much cheaper, right?
We are using Lambda@Edge at my workplace and it scales pretty well.
One thing to take note of though is where you run the Lambda@Edge function. You only get the real Host
header when you run the function in the ViewerRequest
hook which will not be cached. When you execute on the OriginRequest
hook, which is cached, it will replace the Host
header with the origin's Host
header ( For an S3 origin the Host
header would be example-bucket.s3-website-region.amazonaws.com
instead of example-bucket.com
)