将查看器重定向到新的 URL - Amazon CloudFront
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

将查看器重定向到新的 URL

以下函数示例会生成一个响应,以便在请求来自特定国家/地区时将查看器重定向到特定国家/地区的 URL。此函数依赖 CloudFront-Viewer-Country 标头的值来确定查看器所在的国家/地区。

重要

要使此功能起作用,您必须配置为将CloudFront-Viewer-Country标头 CloudFront 添加到缓存策略或源请求策略中允许的标头中,从而将其添加到传入的请求中。

当查看器请求来自德国时,此示例将查看器重定向到德国特定的 URL。如果查看器请求不是来自德国,该函数将返回原始的未修改请求。

这是查看器请求函数。

请看上面的这个例子 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; }

有关重写和重定向的更多信息,请参阅工作室工作室中使用边缘函数处理重写和重定向。Amazon