David's answer points to the docs, which boil down to:
- Create a Lambda function like so. Note that Lambda@Edge has a limited set of runtimes and some additional constraints compared to other Lambda functions. For example, all functions must be created in
us-east-1
- CloudFront will automagically replicate them to other regions - layers are not supported, and all triggers must use an explicit ARN - no aliases, or using $LATEST
.
'use strict';
exports.handler = (event, context, callback) => {
const response = event.Records[0].cf.response;
const headers = response.headers;
headers['strict-transport-security'] = [{
key: 'Strict-Transport-Security',
/*
* verify that max-age and 'includeSubdomains' are the settings you want
*/
value: 'max-age=31536000; includeSubdomains; preload'
}];
callback(null, response);
};
- Publish a version and deploy it to Lambda@Edge. You cannot use
$LATEST
or an alias for the next step.
- Associate the published function version with a CloudFront distribution. If this is a one-off task, it's probably easier to do it via the Lambda console. If you want to associate your function with multple distributions, it's probably easier to use the CloudFront console.
You'll want to set the event type as origin-response
(between S3 and the cache) or viewer-response
(between cache and browser), and specify the ARN with the version you published above - e.g.
arn:aws:lambda:us-east-1:1234567890:function:MY-FUNCTION-NAME:v1
Wait for the distribution to update and test that the headers are present in the response