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

将查看器重定向到新的 URL

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

重要

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

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

这是查看器请求函数。

在 GitHub 上查看此示例

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