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