如何使用 Lambda@Edge 检测用户所在国家/地区并重定向到 /pt 等本地化子文件夹?

How to use Lambda@Edge to detect user country and redirect to localised subfolder like /pt?

我正在使用以下 Lambda@Edge 代码,但不知道如何去做。

以下代码使子目录根索引在 Cloudfront 上运行。

Cloudfront 是否在请求中提供来源国?

'use strict';

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

    // Extract the request from the CloudFront event that is sent to Lambda@Edge 
    var request = event.Records[0].cf.request;

    // Extract the URI and params from the request
    var olduri = request.uri;

    // Match any uri that ends with some combination of 
    // [0-9][a-z][A-Z]_- and append a slash
    var endslashuri = olduri.replace(/(\/[\w\-]+)$/, '/');

    //console.log("Old URI: " + olduri);
    //console.log("Params: " + params);
    //console.log("Mid URI: " + miduri);

    if(endslashuri != olduri) {
        // If we changed the uri, 301 to the version with a slash, appending querystring
        var params = '';
        if(('querystring' in request) && (request.querystring.length>0)) {
            params = '?'+request.querystring;
        }
        var newuri = endslashuri + params;

        //console.log("No trailing slash");
        //console.log("New URI: " + newuri);

        const response = {
            status: '301',
            statusDescription: 'Permanently moved',
            headers: {
                location: [{
                    key: 'Location',
                    value: newuri
                }]
            }
        };
        return callback(null, response);
    } else {
        // Match any uri with a trailing slash and add index.html
        newuri = olduri.replace(/\/$/, '\/index.html');

        //console.log("File or trailing slash");
        //console.log("New URI: " + newuri);

        // Replace the received URI with the URI that includes the index page
        request.uri = newuri;

        // Return to CloudFront
        return callback(null, request);
    }
};

在缓存行为设置中,将 header CloudFront-Viewer-Country 列入白名单以转发到源。来源不需要它,但是一旦您配置了它,您就可以在 Lambda@Edge 来源请求触发器中访问查看者国家/地区:

const cc = (request.headers['cloudfront-viewer-country'] || [ { value: 'XX' } ])[0].value;

如果 CloudFront 无法确定国家/地区代码,请将 'XX' 替换为您要分配给常量 cc 的任何值——例如你的默认值。

您无法从查看器请求触发器访问该国家/地区,但无论如何,Origin Request 是一个更好的选择——来自该触发器的响应(重定向)可以被缓存,这意味着触发器触发的频率较低。 CloudFront 将自动为每个国家/地区代码缓存不同的页面副本,并仅将其提供给同一国家/地区的查看者。