scar icon indicating copy to clipboard operation
scar copied to clipboard

Suggestion: Replace second bucket and CloudFront distribution with Lambda function

Open awkspace opened this issue 5 years ago • 2 comments

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;
    }

};

awkspace avatar May 22 '19 18:05 awkspace

How about the cost of this at scale? The current S3 option would be much cheaper, right?

tschoffelen avatar May 24 '19 07:05 tschoffelen

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)

celioreyes avatar May 29 '19 02:05 celioreyes