我一直在尝试使用lambda @ edge将CloudFront-viewer-country标头添加到我的响应中,我设法触发了该函数及其功能,但是我在cloudWatch中看不到任何日志,cloudWatch仅在记录日志在功能页面上完成的测试不是通过访问网站触发的实际测试,我用谷歌搜索了如何查找日志,并发现它在接收请求的最近区域的cloudWatch中,但是我找不到任何内容。
我尝试了两种方法来更改响应,其中一种是在堆栈溢出答案上:https://stackoverflow.com/questions/48633610/how-do-i-get-cloudfront-viewer-country-to-appear-in-response-headers
'use strict';
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
const response = event.Records[0].cf.response;
if(request.headers['cloudfront-viewer-country'])
{
response.headers['cloudfront-viewer-country'] = request.headers['cloudfront-viewer-country'];
}
return callback(null,response);
};
从lambda页面进行测试时,此方法有效,但是当我通过访问网站进行测试时,我看到503服务器错误:与CloudFront发行版关联的Lambda函数无效或没有所需的权限。
因此有人可以帮助您获得这些权限,请注意,我在静态托管我的网站的s3存储桶上具有以下策略:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadForGetBucketObjects",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:*",
"Resource": "arn:aws:s3:::outfityard-app-client/*"
}
]
}
我尝试过的另一种方法是在我的lambda中使用以下函数:
'use strict';
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
const headers = request.headers;
const uri = request.uri === "/index.html" ? "/" : request.uri;
var countryCode = null;
if(headers["cloudfront-viewer-country"]) {
countryCode = headers["cloudfront-viewer-country"][0].value;
}
console.log(`Country detected: '${countryCode}'`);
if (countryCode !== "US") {
const response = {
status: "200",
statusDescription: "Found",
headers: {
["cache-control"]: [
{
key: "Cache-Control",
value: "no-cache, no-store, private"
}
],
["cloudfront-viewer-country"]: [
{
key: "cloudfront-viewer-country",
value: countryCode
}
]
}
};
callback(null, response);
} else {
callback(null, request);
}
};
此方法返回预期的响应,但没有从我的网站加载任何内容,我不明白为什么!这是我收到的响应标头:
Content-Type →text/html
Content-Length →1217
Connection →keep-alive
Server →CloudFront
Date →Fri, 16 Aug 2019 11:37:19 GMT
X-Cache →LambdaExecutionError from cloudfront
Via →1.1 9891f2220bf61a27cb1f26085ab3703d.cloudfront.net (CloudFront)
X-Amz-Cf-Pop →CDG3-C2
X-Amz-Cf-Id →D542SzvAsMYAXIOcBUwHWEB5_lAf41t1wWULh6LcXwagAvjFRvH5nA==
我已经使用了以下内容,并且可以正常工作,但是我不知道它是否正确:
'use strict';
exports.handler = (event, context, callback) => {
const request = event.Records[0].cf.request;
const response = event.Records[0].cf.response;
const value = request.headers['cloudfront-viewer-country'][0].value;
const key = request.headers['cloudfront-viewer-country'][0].key;
response.headers['cloudfront-viewer-country'] = [{key: key, value: value}];
return callback(null,response);
};