仅当满足条件时 AWS Lambda 触发器功能

AWS Lambda trigger function only if conditions are met

我刚刚开始学习 AWS Lambda 和 CloudFront。 我发现操作请求和响应很容易,但我无法完成一个简单的任务。

鉴于下面的代码,我只想在用户没有 /it/ 或 /en/ 的情况下触发操作 request.uri

我在解析 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);  
};

如果我没记错的话,你缺少的部分是 if,因为你只有 else

exports.handler = async (event, context, callback) => {

    // const
    const request = event.Records[0].cf.request;
    const headers = request.headers;


    if (headers['cloudfront-viewer-country']) {
        // non IT url
        let url = '/en/';
        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); 
    }

    // There is no need to redirect
    callback(null, request);

};

所以基本上如果 URL 有 IT 或 EN,就让它通过 whit: callback(null, request);

您可能会发现 this example from the docs useful for your case