AWS ALB 从 Lambda 返回 502 而不是自定义 HTTP 状态

AWS ALB returning 502 from Lambda instead of custom HTTP status

我创建了一个 Lambda 来检查 DynamoDB table 是否存在匹配主机和请求路径的记录,如果找到,return 重定向到匹配 URL.

我的 Lambda return 是这个响应,但是 ALB return 是 502。

{
    "statusCode": 301,
    "statusDescription": null,
    "headers": {
        "Location": "https://www.my-target.co.uk/"
    },
    "multiValueHeaders": null,
    "body": "Redirecting to https://www.my-target.co.uk/",
    "isBase64Encoded": false
}

这是我在 CloudWatch 中找到的 Lambda 函数的日志

START RequestId: 8b5a28f2-c56d-4418-a7b9-66ebe0ba2470 Version: $LATEST
[Information] EMG.ApplicationLoadBalancerRequestHandler: Received: GET / 
[Information] EMG.ApplicationLoadBalancerRequestHandler: Processing: my-test.net / 
[Information] EMG.RedirectManagers.RedirectTableRedirectManager: Fetching item: my-test.net / from table redirect-table 
[Information] EMG.ApplicationLoadBalancerRequestHandler: Found: https://www.target.co.uk/ Permanent 
END RequestId: 8b5a28f2-c56d-4418-a7b9-66ebe0ba2470
REPORT RequestId: 8b5a28f2-c56d-4418-a7b9-66ebe0ba2470  Duration: 69.59 ms  Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 39 MB  

这是我得到的回复

HTTP/1.1 502
status: 502
Server: awselb/2.0
Date: Thu, 15 Aug 2019 19:13:58 GMT
Content-Type: text/html
Content-Length: 138
Connection: keep-alive
<html>
 <head><title>502 Bad Gateway</title></head>
 <body bgcolor="white">
 <center><h1>502 Bad Gateway</h1></center>
 </body>
 </html>

我找不到任何说我们不能 return 来自 Lambda 的非 200 响应的内容,所以我真的不知道...

您也可以在相关的 GitHub 回购中找到这个问题:https://github.com/aws/aws-lambda-dotnet/issues/507

显然我缺少返回的 HTTP 响应中必需的 属性。

这是AWS documentation(强调我的)的相关部分

The response from your Lambda function must include the Base64 encoding status, status code, status description, and headers. You can omit the body. The statusDescription header must contain the status code and reason phrase, separated by a single space.

更改我的代码以使 Lambda 的响应符合要求解决了问题。

{
    "statusCode": 301,
    "statusDescription": "301 Found",
    "headers": {
        "Location": "https://www.my-target.co.uk/"
    },
    "multiValueHeaders": null,
    "body": "Redirecting to https://www.my-target.co.uk/",
    "isBase64Encoded": false
}