文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 AWS SDK 範例。
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
在 CloudFront Functions 檢視器請求事件中重新導向至新 URL
下列程式碼範例示範如何在 CloudFront Functions 檢視器請求事件中重新導向至新 URL。
- JavaScript
-
- 適用於 CloudFront Functions 的 JavaScript 執行時期 2.0
-
async 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;
}