'AWS Lambda@Edge URL redirected you too many times

I have created a lambda to redirect users based on country location using cloudfront distribution. but I am facing this issue where the url is being redirected too many times.

When user connects from BR country it's redirecting to https://xxxxxxxx.cloudfront.net/pt.example.com instead of just pt.example.com (BR) or example.com for the other countries.

'use strict';

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

let url = 'example.com';
console.log(JSON.stringify(headers, null, 2));


// const host_address = headers.host[0].value;


if (headers['cloudfront-viewer-country']) {
    const countryCode = headers['cloudfront-viewer-country'][0].value;
    if (countryCode == 'BR') {
        url = 'pt.example.com';
    }
}

const response = {
    status: '302',
    statusDescription: 'Found',
    headers: {
        location: [{
            key: 'Location',
            value: url,
        }],
        'cache-control': [{
        key: 'Cache-Control',
        value: "max-age=3600"
      }],
    },
};


callback(null, response); };

I have created the distribution with CloudFront-Viewer-Country header and set the lambda as request from origin

any idea why this is not working properly?



Solution 1:[1]

Check your Cloudfront origin and verify that the Origin path - optional is empty. Otherwise Cloudfront will append the url with whatever is there.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohamed