Domain redirects for CloudFront

In 2019, the site covered www-redirects using Lambda@Edge. While that approach remains functional, AWS CloudFront introduced a newer feature: CloudFront Functions. This tool simplifies domain redirects and reduces costs compared to the previous method.

Key Differences Between Solutions

CloudFront Functions and Lambda@Edge serve different purposes. Functions operate only at viewer-request and viewer-response stages, whereas Lambda@Edge handles origin-request and origin-response events too. The JavaScript environment in Functions has restricted capabilities and lacks network access, preventing API calls or AWS service integration.

Despite limitations, Functions excel at straightforward modifications like domain redirects and blocking traffic to default cloudfront.net domains.

Implementation Steps

Use the following code with "Viewer Request" event type, customizing the mainDomain variable:

function handler(event) {
    var request = event.request;
    var headers = request.headers;
    var uri = request.uri;
    var mainDomain = "grrr.tech";

    if (headers.host.value !== mainDomain) {
        return {
            statusCode: 301,
            statusDescription: "Moved Permanently",
            headers: {
                location: { value: "https://" + mainDomain + uri },
            },
        };
    }

    return request;
}

The function examines the request's domain and redirects non-matching traffic to the primary domain.

Troubleshooting Approaches

External logging isn't available since Functions can't communicate externally. Custom headers offer debugging capability. Execute curl -I https://your-distribution-url.cloudfront.net to inspect response headers.

function handler(event) {
    var request = event.request;
    var headers = request.headers;
    var uri = request.uri;

    return {
        statusCode: 200,
        statusDescription: "OK",
        headers: {
            "x-debug-header": { value: uri },
        },
    };
}

Note that Functions cannot modify response bodies—another distinction from Lambda@Edge.

Originally published on norday.tech.