【发布时间】:2020-02-22 03:36:02
【问题描述】:
我刚刚开始学习 AWS Lambda 和 CloudFront。 我发现操作请求和响应非常容易,但我无法完成一个简单的任务。
鉴于下面的代码,我只想在用户在request.uri 中没有 /it/ 或 /en/ 的情况下触发操作
我在解析 uri 字符串时没有问题,但我不确定如何实现这个非常简单的逻辑:
if(uri contains 'it' or 'en') {
proceed as normal and forward request to origin
} else {
return a 301 response with '/it' or '/en' based on user language
}
下面用 node.js 编写的函数部分完成了这项工作,它在我的 CloudFront 发行版中的 Viewer Request 中触发:
exports.handler = async (event, context, callback) => {
// const
const request = event.Records[0].cf.request;
const headers = request.headers;
// non IT url
let url = '/en/';
if (headers['cloudfront-viewer-country']) {
const countryCode = headers['cloudfront-viewer-country'][0].value;
if (countryCode === 'IT') {
url = '/it/';
}
}
const response = {
status: '301',
statusDescription: 'geolocation',
headers: {
location: [{
key: 'Location',
value: url,
}],
},
};
callback(null, response);
};
【问题讨论】:
标签: node.js amazon-cloudfront aws-lambda-edge