要将HTTP重定向到HTTPS,您可以使用API网关的请求转发功能。以下是一个示例代码,可以在API网关中使用:
import json
def lambda_handler(event, context):
request = event['Records'][0]['cf']['request']
headers = request['headers']
# 检查X-Forwarded-Proto头部以确定原始请求的协议
if headers['x-forwarded-proto'][0]['value'] == 'http':
# 构建重定向URL
redirect_url = 'https://' + headers['host'][0]['value'] + request['uri']
# 构建重定向响应
response = {
'status': '302',
'statusDescription': 'Found',
'headers': {
'location': [{
'key': 'Location',
'value': redirect_url
}]
}
}
return response
# 如果原始请求已经是HTTPS,则直接转发请求
return request
此代码在Lambda函数中运行,作为API网关的请求转发函数。它检查原始请求的协议是否为HTTP,并根据需要构建重定向URL。然后,它构建一个重定向响应,将请求重定向到HTTPS。如果原始请求已经是HTTPS,则直接转发请求。