0

I have just started my learning path with AWS Lambda and CloudFront. I found quite easy to manipulate request and response, but I am blocked to achieve a simple task.

Given the code below, I wanted to trigger actions only in the case where the user doesn't have a /it/ or /en/ in the request.uri

I have no problem in parsing the uri string but I am unsure on how to achieve this very simple logic:

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
}

the function below written in node.js does this job partially, it is triggered in Viewer Request in my CloudFront distribution:

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);  
};
Leonardo
  • 9,607
  • 17
  • 49
  • 89

1 Answers1

0

If Im not wrong the part you are missing is the if, as you only have the 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);

};

So basically if the URL has the IT or EN, just let it go trough whit: callback(null, request);

You might find this example from the docs useful for your case

Gonz
  • 1,198
  • 12
  • 26
  • Basically, what I was missing is to add `callback(null, request)` at the end. In this case infact no redirect happens and the request is passed to the origin as is. – Leonardo Dec 18 '19 at 05:30