由于AWS Cloudfront不能识别不同云前端之间的域名重定向,解决方案是使用Lambda函数将HTTP 3xxs状态码重定向请求发送到原始域名,以便Cloudfront可以加载正确的资源。
代码示例:
import json
import urllib.parse
def lambda_handler(event, context):
# 获取原始请求信息
request = event['Records'][0]['cf']['request']
headers = request['headers']
host = headers['host'][0]['value']
uri = request['uri']
method = request['method']
# 将HTTP 3xx状态码重定向请求发送到原始域名
if method == 'GET' and int(request['status']) > 299 and int(request['status']) < 400:
response = {
'status': '301',
'statusDescription': 'Moved Permanently',
'headers': {
'location': [{
'key': 'Location',
'value': 'https://' + host + uri
}]
}
}
return response
# 没有重定向则返回原始请求
return request