从 Lambda@Edge 函数获取客户端请求域

hsk*_*hsk 5 javascript node.js amazon-cloudfront aws-lambda aws-lambda-edge

我正在尝试对 HTTP 301 重定向执行如下操作,以便网络用户将重定向到不同的新闻页面。

    if ((request.uri == "/news") || (request.uri == "/news/") && (request.origin.domainName == "sub.mydomain.com")) {

        
        const redirectResponse = {
            status: '301',
            statusDescription: 'Moved Permanently',
            headers: {
                'location': [{
                    key: 'Location',
                    value: '/local-news/',
                }],
                'cache-control': [{
                    key: 'Cache-Control',
                    value: "max-age=3600"
                }],
            },
        };
        callback(null, redirectResponse);
   
  }
Run Code Online (Sandbox Code Playgroud)

但是,似乎这个request.origin.domainName == "mydomain.com"部分在我的函数中不起作用。这是选择客户端来自的域名的正确方法吗?

我认为此request.origin.domainName方法将无法作为仅适用于Origin 请求的Origin对象支持。我是否有可能获得查看者请求的客户端的域名?

我需要这个的原因是,我有多个域,用户访问相同的 CloudFront 发行版。因此,当用户来自不同域时,必须将用户重定向到不同的新闻网站。

有人可以支持我吗?

Cyb*_*nal 4

If you want to get distribution Domain Name

  const distributionDomain = event.Records[0].cf.config.distributionDomainName;
Run Code Online (Sandbox Code Playgroud)

The more information You can find in AWS Documentation

Also, check

Lambda@Edge Example Functions

Doc

accessing origin URL from AWS lambda@edge

Also, try this way

'use strict';

exports.handler = (event, context, callback) => {
    const response = event.Records[0].cf.response;
    const request = event.Records[0].cf.request;
    const hostHeader = request.headers['host'][0].value;
    callback(null, response);
};
Run Code Online (Sandbox Code Playgroud)

hostHeader should be the CNAME(domain name)

The more info here