cloudkj / scar

Deploy static websites in seconds - with HTTPS, a global CDN, and custom domains.
MIT License
1.74k stars 61 forks source link

Suggestion: Replace second bucket and CloudFront distribution with Lambda function #2

Open awkspace opened 5 years ago

awkspace commented 5 years ago

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

};
tschoffelen commented 5 years ago

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

celioreyes commented 5 years ago

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 ofexample-bucket.com)