將檢視者重新導向至新的 URL - Amazon CloudFront

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

將檢視者重新導向至新的 URL

下列範例函數會產生回應,以便在請求來自特定國家/地區內時,將檢視者重新導向至特定國家/地區的 URL。此函數會依賴 CloudFront-Viewer-Country 標頭的值來判斷檢視者所在的國家/地區。

當檢視者請求來自德國時,這個範例會將檢視者重新導向至德國特定的 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; }

有關重寫和重定向的更多信息,請參閱在AWS工作室中使用邊緣函數處理重寫和重定向。