Lukas Z's Blog

AWS: How to Change S3 Response Headers

I have S3 buckets that I use to serve public assets with (behind CloudFront, with a custom domain name). However the response always included the header field “Server” with a value “AmazonS3”. I didn’t like to publish the fact that I was using S3 (because what for?) and I wondered If I could change that string.

It’s not entirely straightforward, but not difficult either.

Here’s how I did it:

  1. Set up S3 buckets

  2. Set up CloudFront for these buckets

  3. Set up a Lambda (Lambda@Edge only, this means us-east-1, N. Virginia)

  4. Insert code (see below)

  5. Actions/publish new version (must be versioned Lambda)

  6. Select version and add CloudWatch triggers. NOTE: Make sure you use the event type “origin-response”.

  7. Ensure permissions for Lambda (logs:CreateLogStream, logs:PutLogEvents, logs:CreateLogGroup, maybe others..)

  8. Set up trust relationship for lambda role, see below.

Note that depending on you CloudFront setup it can take a while for your changes to become visible. I used the “Invaldations” feature to invalidate the cache for some urls.

Lambda Code:

'use strict';

exports.handler = (event, context, callback) => {
    const response = event.Records[0].cf.response;
    response.headers['server'] = [{
        key: 'Server',
        value: 'Whatever you like',
    }];

    callback(null, response);
};

Trust Relationships:

"Service": ["lambda.amazonaws.com", "edgelambda.amazonaws.com"]

This is all based on this useful blogpost, definitely check it out: https://nvisium.com/resources/blog/2017/08/10/lambda-edge-cloudfront-custom-headers.html

P.S.: You can follow me on Twitter.

Comments

Webmentions