diff --git a/redirect_maintain_uri_querystring/index.js b/redirect_maintain_uri_querystring/index.js new file mode 100644 index 0000000..eca1d9a --- /dev/null +++ b/redirect_maintain_uri_querystring/index.js @@ -0,0 +1,34 @@ +function objectToQueryString(obj) { + var str = []; + for (var param in obj) + if (obj[param].multiValue) + str.push(param + "=" + obj[param].multiValue.map((item) => item.value).join(',')); + else if (obj[param].value == '') + str.push(param); + else + str.push(param + "=" + obj[param].value); + + return str.join("&"); +} + +function handler(event) { + var request = event.request; + var headers = request.headers; + var uri = request.uri; + var loc = ""; + var newdomain = "newdomain.com"; + + if (Object.keys(request.querystring).length) + loc = `https://${newdomain}${uri}?${objectToQueryString(request.querystring)}` + else + loc = `https://${newdomain}${uri}` + + var response = { + statusCode: 302, + statusDescription: 'Found', + headers: { + 'location': { value: `${loc}` } + } + }; + return response; +} diff --git a/redirect_maintain_uri_querystring/readme.md b/redirect_maintain_uri_querystring/readme.md new file mode 100644 index 0000000..51bbc68 --- /dev/null +++ b/redirect_maintain_uri_querystring/readme.md @@ -0,0 +1,28 @@ +## Redirect (temporary) to new domain + +**CloudFront Functions event type: viewer response** + +This function will perform a redirect (302 - temporary) to a new domain while maintaining the uri and query string values in the destination FQDN. + +If you want a permanent redirect, change statusCode from 302 to 301 in function code. + +**Important: Set the `newdomain` variable to an appropriate value for your specific needs.** + +**Testing the function** + +To validate that the function is working as expected, you can use the provided test object from https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/functions-event-structure.html#functions-event-structure-example and test in the console using the instructions https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/test-function.html#test-function-console. + +If the function has been set up correctly, you should see a result similar to the following with the value of 'newdomain', and the uri and querystring values from the test object being added in the 'location' response header in `FunctionOutput` JSON object: +``` +{ + "response": { + "headers": { + "location": { + "value": "https://newdomain.com/media/index.mpd?ID=42&Exp=1619740800&TTL=1440&querymv=val1,val2,val3" + } + }, + "statusDescription": "Found", + "cookies": {}, + "statusCode": 302 + } + ...