Fix Redirections on GitHub Pages and CloudFront

For a website that uses GitHub Pages and CloudFront, users can end up at your original GH Pages hostname when it sends a 301 redirection.

GH Pages redirects clients at some circumstances like accessing a directory without a trailing /, etc. This is a problem especially if you are using CF to route requests based on paths, or need TLS and using a custom domain.

CloudFront allows Lambda functions to process requests and responses of both viewers and origins. It currently only supports nodejs6.10 runtime property and has a few restrictions but it allows me to address this specific problem.

Get Started

Create a function from scratch (or modify the cloudfront-modify-response-header blueprint). The execution role of the function can be created from the Basic Edge Lambda permissions template. After editing and testing the function, add a trigger, select your CF distribution and Origin Request event.

The following script replaces http://gh-pages.example.com with https://www.example.com in the Location response header.

'use strict';

exports.handler = (event, context, callback) => {
    const response = event.Records[0].cf.response;
    const headers = response.headers;

    // Find Location header (all in lowercase)
    const headerLocation = headers['location'];
    if (headerLocation) {
        var url = headerLocation[0]['value'];

        // Update protocol and hostname
        url = url.replace(/http:\/\/gh-pages\.example\.com/i,
                          'https://www.example.com');

        headerLocation[0]['value'] = url;
    }
    callback(null, response);
};