Search code examples
amazon-web-servicesamazon-s3aws-lambdaamazon-cloudfrontaws-lambda-edge

How to stop domain redirects when using a CloudFront domain as the custom origin at Lambda@Edge?


I want to use different origins according to the relative paths of my website.

My root domain is example.com and it should be served with example01.cloudfront.net and example.com/pathxx/ should be served with example02.cloudfront.net. These two CloudFront distributions are linked to two s3 buckets with static sites.

I have mapped the example.com to another CloudFront distribution. Following is the code I'm using at the Lambda@Edge on that Cloudfront distribution's origin-request trigger.

exports.handler = async (event, context, callback) => {
    var request = event.Records[0].cf.request;

    let domain = "";
    if (request.uri.match(/\/pathxx\//)) {
      domain = "example02.cloudfront.net";
      request.uri = request.uri.replace(/\/pathxx\//,"/");
    } else {
      domain = "example01.cloudfront.net";
    }

    request.origin = {
          custom: {
            domainName: domain,
            port: 80,
            protocol: "http",
            path: "",
            sslProtocols: ["TLSv1", "TLSv1.1"],
            readTimeout: 5,
            keepaliveTimeout: 5,
            customHeaders: {}
          }
    };
    
    request.headers["host"] = [{ key: "host", value: domain }];
    callback(null, request);
};

When I used this code and enter example.com on the browser then it redirects to the example01.cloudfront.net and example.com/pathxx redirects to the example02.cloudfront.net by receiving 301 status codes.

But if I change the CloudFront origins to their s3 bucket URLs then this redirection doesn't occur and I will see my example.com domain always as I'm expecting and I will not receive any 301 codes which causes redirects.

...
    if (request.uri.match(/\/pathxx\//)) {
      domain = "example02.s3.amazonaws.com";
      request.uri = request.uri.replace(/\/pathxx\//,"/");
    } else {
      domain = "example01.s3.amazonaws.com";
    }
...

Is that means we can't use CloudFront distribution domains as custom origins??

Due to caching issues, I must use CloudFront domains for the custom origins therefore I cannot use s3 bucket URLs. This is a limitation on my project's architecture and also using CloudFront domains meant to achieve pre-caching also.


Solution

  • I just found the answer at here:

    CloudFront seems to be going through the HTTP to HTTPS redirection when it tries to use the CloudFront origins and as a result my domain changes on the browser.

    So, I did change my two CloudFront distributions (example01.cloudfront.net and example02.cloudfront.net) to use "HTTP and HTTPS" option for the Viewer Protocol Policy of the origin on the Behaviors tab. So they will not redirect to HTPPS forcefully anymore.