1. Lambda@Edge的概念
每个 Lambda@Edge 函数都必须包含 callback
参数,以成功处理请求或返回响应
2. Lambda@Edge在CloudFront 的应用
(1)A/B测试
如果要测试主页的两种不同版本,但是不想创建重定向或更改 URL,则可使用以下示例。此示例会在 CloudFront 接收到请求时设置 Cookie,随机将用户分配至版本 A 或 B,然后将相应的版本返回到查看器。
import json
import random
def lambda_handler(event, context):
request = event['Records'][0]['cf']['request']
headers = request['headers']
if request['uri'] != '/experiment-pixel.jpg':
# Not an A/B Test
return request
cookieExperimentA, cookieExperimentB = 'X-Experiment-Name=A', 'X-Experiment-Name=B'
pathExperimentA, pathExperimentB = '/experiment-group/control-pixel.jpg', '/experiment-group/treatment-pixel.jpg'
'''
Lambda at the Edge headers are array objects.
Client may send multiple cookie headers. For example:
> GET /viewerRes/test HTTP/1.1
> User-Agent: curl/7.18.1 (x86_64-unknown-linux-gnu) libcurl/7.18.1 OpenSSL/1.0.1u zlib/1.2.3
> Cookie: First=1; Second=2
> Cookie: ClientCode=abc
> Host: example.com
You can access the first Cookie header at headers["cookie"][0].value
and the second at headers["cookie"][1].value.
Header values are not parsed. In the example above,
headers["cookie"][0].value is equal to "First=1; Second=2"
'''
experimentUri = ""
for cookie in headers.get('cookie', []):
if cookieExperimentA in cookie['value']:
print("Experiment A cookie found")
experimentUri = pathExperimentA
break
elif cookieExperimentB in cookie['value']:
print("Experiment B cookie found")
experimentUri = pathExperimentB
break
if not experimentUri:
print("Experiment cookie has not been found. Throwing dice...")
if random.random() < 0.75:
experimentUri = pathExperimentA
else:
experimentUri = pathExperimentB
request['uri'] = experimentUri
print(f"Request uri set to {experimentUri}")
return request
(2)覆盖响应标头
(3)添加HTTP security headers
(4)提供静态内容
(5)重定向:比如将未通过身份验证的用户定向到登陆页面