I had a CloudFront distribution using the legacy cache Behavior and Aws Lambda Edge to change the origin path to serve multiple websites using the same bucket.
This was my lambda edge that was working with the legacy cache behavior:
|
'use strict';
const env = '${Environment}';
const origin_hostname = 'yourwebsite-${Environment}.s3.amazonaws.com';
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
const headers = request.headers;
const host_header = headers.host[0].value;
var remove_suffix = '.yourwebsite.com';
if(env == "dev"){
remove_suffix = '-dev.yourwebsite.com';
}
if(host_header.endsWith(remove_suffix))
{
request.uri = '/' + host_header.substring(0,host_header.length - remove_suffix.length) + request.uri;
}
// fix the host header so that S3 understands the request
headers.host[0].value = origin_hostname;
// return control to CloudFront with the modified request
return callback(null,request);
};
This was my CloudFormation Lambda function association and cache policies:
LambdaFunctionAssociations:
- EventType: origin-request
LambdaFunctionARN: !Ref HotSitesEdgeFunctionVersion
CachePolicyId: "658327ea-f89d-4fab-a63d-7e88639e58f6"
ResponseHeadersPolicyId: "67f7725c-6f97-4210-82d7-5512b31e9d03"