ビューワーを新しい URL にリダイレクトさせる - Amazon CloudFront

ビューワーを新しい 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; }

リライトとリダイレクトの詳細については、「AWS workshop studio」の「エッジ関数を使用したリライトとリダイレクトの処理」を参照してください。