将CloudFront域用作Lambda @ Edge的自定义来源时,如何停止域重定向? Route53 Cloudfront发行版A

问题描述

我想根据网站的相对路径使用不同的来源。

我的根域是 example.com ,并且应该与 example01.cloudfront.net 一起使用 和 example.com/pathxx / 应该与 example02.cloudfront.net 一起使用。 这两个CloudFront发行版链接到具有静态站点的两个s3存储桶。

我已将 example.com 映射到另一个CloudFront发行版。 以下是我在该Cloudfront发行版的原始请求触发器上的Lambda @ Edge上使用的代码

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

    let domain = "";
    if (request.uri.match(/\/pathxx\//)) {
      domain = "example01.cloudfront.net";
      request.uri = request.uri.replace(/\/pathxx\//,"/");
    } else {
      domain = "example02.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);
};

当我使用此代码并在浏览器中输入 example.com 时,它将重定向 example01.cloudfront.net example.com/pathxx 通过接收301状态代码重定向 example02.cloudfront.net

但是,如果我将CloudFront来源更改为它们的s3存储桶URL,则不会发生这种重定向,并且我会一直按预期看到我的example.com域,并且不会收到任何导致重定向的301代码。 / p>

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

这意味着我们不能将CloudFront分发域用作自定义来源?

由于缓存问题,我必须将CloudFront域用于自定义来源,因此我不能使用s3存储桶URL。这是对我的项目架构的限制,并且还使用了旨在实现预缓存的CloudFront域。

解决方法

我刚刚在here找到了答案:

当CloudFront尝试使用CloudFront来源时,似乎正在通过HTTP到HTTPS重定向,结果我的域在浏览器上发生了变化。

因此,我确实更改了两个CloudFront发行版(example01.cloudfront.net和example02.cloudfront.net),以将“ HTTP和HTTPS ”选项用于查看器协议策略“行为”选项卡上的原点的“ strong>”。因此,它们将不会再强制重定向到HTPPS。

,

可以将单个Cloudfront发行版配置为提供来自多个来源(例如2个不同的S3存储桶)的内容。因此,您可以(完全不使用Lambda)拥有:

Route53

  • example.com-> CloudFront分散A

Cloudfront(发行版A)

  • example.com/*->原始s3-bucket-1
  • example.com/pathx/->原始s3-bucket-2

有关演练(请参见this guide(使用API​​ Gateway + S3)。