CloudFrontでオリジンにアクセスするHostヘッダを書き換える方法
これを参考にした。
Lambda@Edgeで実装するときのコードは以下のようになる。
import { CloudFrontRequestEvent, CloudFrontRequestResult, Context, Handler,} from "aws-lambda";
const testDomainSuffix = ".testdevhost.gigaviewer.com";const domainSuffix = ".devhost.gigaviewer.com";
export const handler: Handler< CloudFrontRequestEvent, CloudFrontRequestResult> = (event: CloudFrontRequestEvent, context: Context, callback) => { const request = event.Records[0]?.cf.request; if (request?.origin?.custom?.domainName !== undefined) { const name = request.origin.custom.domainName; if (name.endsWith(testDomainSuffix)) { const branch = name.substring(0, name.length - testDomainSuffix.length); request.origin.custom.domainName = branch + domainSuffix; request.headers["host"] = [{ key: "host", value: branch + domainSuffix }]; } } callback(null, request);};このとき、Lambda@EdgeとCloudFront Functionsで出来ることが異なる。例えばCloudFront Functionsの場合は viewer-request イベントだけ Host: ヘッダの書き換えができる。Lambda@Edgeの場合は origin-request でしか書き換えられない。
各イベントではLambda@EdgeまたはCloudFront Functionsどちらかひとつだけしかトリガーできないので、例えば viewer-request イベントを別の用途に使っていたら origin-request でLambda@Edgeを利用するしかない。