1

我正在使用以下 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\-]+)$/, '$1/');

    //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);
    }
};
4

1 回答 1

2

In the Cache Behavior settings, whitelist the header CloudFront-Viewer-Country for forwarding to the origin. The origin doesn't need it, but once you configure this, then you have access to the viewer country in a Lambda@Edge Origin Request trigger:

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

Replace 'XX' with whatever value you want to assign to the constant cc if CloudFront can't determine a country code -- e.g. your default.

You can't access the country from a Viewer Request trigger, but Origin Request is a better choice anyway -- responses (the redirects) from this trigger can be cached, meaning the trigger fires less often. CloudFront will automatically cache a different copy of the page for each country code and serve it only to viewers in the same country.

于 2018-10-23T01:32:24.133 回答