Redirect the viewer to a new URL - Amazon CloudFront
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Redirect the viewer to a new URL

The following example function generates a response to redirect the viewer to a country-specific URL when the request comes from within a particular country. This function relies on the value of the CloudFront-Viewer-Country header to determine the viewer’s country.

Important

For this function to work, you must configure CloudFront to add the CloudFront-Viewer-Country header to incoming requests by adding it to the allowed headers in a cache policy or an origin request policy.

This example redirects the viewer to a Germany-specific URL when the viewer request comes from Germany. If the viewer request doesn’t come from Germany, the function returns the original, unmodified request.

This is a viewer request function.

See this example on GitHub.

JavaScript runtime 2.0
async function handler(event) { const request = event.request; const headers = request.headers; const host = request.headers.host.value; const country = Symbol.for('DE'); // Choose a country code const newurl = `https://${host}/de/index.html`; // Change the redirect URL to your choice if (headers['cloudfront-viewer-country']) { const countryCode = Symbol.for(headers['cloudfront-viewer-country'].value); if (countryCode === country) { const response = { statusCode: 302, statusDescription: 'Found', headers: { "location": { "value": newurl } } } return response; } } return request; }
JavaScript runtime 1.0
function handler(event) { var request = event.request; var headers = request.headers; var host = request.headers.host.value; var country = 'DE' // Choose a country code var newurl = `https://${host}/de/index.html` // Change the redirect URL to your choice if (headers['cloudfront-viewer-country']) { var countryCode = headers['cloudfront-viewer-country'].value; if (countryCode === country) { var response = { statusCode: 302, statusDescription: 'Found', headers: { "location": { "value": newurl } } } return response; } } return request; }

For more information about rewrites and redirects, see Handling rewrites and redirects using edge functions in the Amazon workshop studio.