2023.05.30
社内勉強会開催!~UI/UXについて~
2023.03.09
インフラCloudFront+Lambda@EdgeでHTTPリダイレクト
– サイトの移設を行う際に、パスの構造が変わる部分についてリダイレクトをする
– 移設後のサイトはCloudFrontでキャッシュしているため、CloudFront側でリダイレクトを行う必要がある
– 当初CloudFrontFunctionsで対応していたが、コード量10KBまでしか扱えないため、およそ100件を超えるようなに対応できない→Lambda@Edgeで実現する
CloudFront Functionsでの方法
https://dev.classmethod.jp/articles/http-redirect-using-cloudfrontfunctions/
Lambda@Edgeでの方法
https://qiita.com/kooohei/items/7fcbc3602f7b7026b5a8
比較
https://qiita.com/hirai-11/items/c9339c88820d01fe0acb
※Lambda@edgeで利用する関数はバージニア北部(us-east-1)である必要があります。東京リージョンで作るとCloudFrontにアタッチする際に以下のようなエラーとなる。
The function must be in region ‘us-east-1’. ARN: arn:aws:lambda:ap-northeast-1:xxxxxxx:function:関数名
[Lambda]-[関数]-[関数の作成]
関数名
なんか適当につけて
ランタイム
Python3.9
コードに以下を張り付けて[Deploy]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
def lambda_handler(event, context): dic = { '/path/to/old/' : 'https://domain/path_to_new/', '/path/to/old1/index.html' : 'https://domain/path_to_new2/hogehoge.html', '/path_to_old/?n=xxxx' : 'https://other_domain/path_to_new3/fugafuga.html' } request = event['Records'][0]['cf']['request'] uri = request['uri'] querystring = request['querystring'] if querystring: uri += '?' + querystring if uri not in dic: return request response = { 'status': '302', 'statusDescription': 'Found', 'headers': { 'location': [{ 'key': 'Location', 'value': dic[uri] }] } } return response |
テンプレート:CloudFron-tAccess-request-in-response
1 2 3 |
"uri": "/path/to/old/", "querystring": "n=xxxx", "method": "GET" |
この辺書き換えてテストを実施。
問題なければバージョンを発行する
[新しいバージョンを発行]
→生成されたARNを以下の作業で利用するのでコピーしておく
Lambda@Edgeを利用するためにはIAMロールの信頼関係を以下のように修正する必要があります。
[Lambda]-[関数]-[関数名]-[アクセス権限]-[実行ロール]
該当のロール-[信頼関係]を以下のように修正
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "edgelambda.amazonaws.com", "lambda.amazonaws.com" ] }, "Action": "sts:AssumeRole" } ] } |
[CloudFront]-[ディストリビューション]-対象ID-[ビヘイビア]-[編集]
パスパターン設定の「関数の関連付け」で
ビューワーリクエスト
関数タイプ:Lambda@Edge
関数:上記で取得したARN
として
[変更を保存]
※CloudFrontのデプロイには少し時間がかかるのでお待ちください
【テクノモバイルではエンジニア/デザイナーを積極採用中です!】
下記項目に1つでも当てはまる方は是非、詳細ページへ!Qangaroo(カンガルー)
最近の記事
タグ検索
SNS共有