Lambda@Edge( Nodejs )でリダイレクト設定をする
はじめに
今回はLambda@Edge( Python3 )を使ってリダイレクト設定しました。 本記事ではLambda@Edgeについてしか触れないので、構成やCloudFront、Lambda@Edgeの設定については下記の記事に記載しています。 下記の記事はPython3で実装しており、本記事は一部のパターンを省略していますがその記事のNodejs版になります。
Lambda@Edgeについて
コードと動作確認
今回は動作確認にLambdaのテスト機能を使ってテストイベントを利用して確認しました。
すべてのリクエストを別ホストにリダイレクトする場合
- redirect.js
'use strict'; var REDIRECT_TARGET_URL = 'http://fuga.cloudfront.net'; exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; var redirectResponse = { status: '301', statusDescription: 'Moved Permanently', body: 'Authentication Failed', headers: { 'location': [ { key: 'Location', value: REDIRECT_TARGET_URL } ] }, } callback(null, redirectResponse); }
動作確認
- テストイベントデータ
host.value
= hoge.cloudfront.net
{ "Records": [ { "cf": { "config": { "distributionId": "EXAMPLE" }, "request": { "headers": { "host": [ { "key": "Host", "value": "hoge.cloudfront.net" } ], "user-name": [ { "key": "User-Name", "value": "CloudFront" } ] }, "clientIp": "0.0.0.0", "uri": "/index.html", "method": "GET" }, "response": { "status": "200", "statusDescription": "OK", "headers": { "x-cache": [ { "key": "X-Cache", "value": "Hello from Cloudfront" } ] } } } } ] }
- 実行結果
{ "status": "301", "statusDescription": "Moved Permanently", "body": "Authentication Failed", "headers": { "location": [ { "key": "Location", "value": "http://fuga.cloudfront.net" } ] } }
- 結果を確認
status
が301
に。location
がhttp://fuga.cloudfront.net
に。
特定のパス配下のアクセスを同じホストの別パスにリダイレクトする (/v1/ -> /v2)/
hoge.cloudfront.net/v1/index.html --> hoge.cloudfront.net/v2/index.html
- redirect.js
'use strict'; var PATH_PATTERN = '^\/v1\/'; exports.handler = (event, context, callback) => { const request = event.Records[0].cf.request; const headers = request.headers; const host = headers.host[0].value; const uri = request.uri; const redirectURL = 'http://' + host + '/v2/index.html' if (uri.match(PATH_PATTERN)) { var redirectResponse = { status: '301', statusDescription: 'Moved Permanently', body: 'Authentication Failed', headers: { 'location': [ { key: 'Location', value: redirectURL } ] }, } callback(null, redirectResponse); } callback(null, request) }
動作確認
- テストイベントデータ
host.value
=hoge.cloudfront.net
uri
=/v1/index.html
{ "Records": [ { "cf": { "config": { "distributionId": "EXAMPLE" }, "request": { "headers": { "host": [ { "key": "Host", "value": "hoge.cloudfront.net" } ], "user-name": [ { "key": "User-Name", "value": "CloudFront" } ] }, "clientIp": "0.0.0.0", "uri": "/v1/index.html", "method": "GET" }, "response": { "status": "200", "statusDescription": "OK", "headers": { "x-cache": [ { "key": "X-Cache", "value": "Hello from Cloudfront" } ] } } } } ] }
- 結果を確認
status
が301
に。location
がhttp://hoge.cloudfront.net/v2/index.html
に。