可以使用AWS Lambda函数和Amazon CloudFront的自定义起源以实现此目的。
import boto3
s3 = boto3.resource('s3')
def handler(event, context):
# Retrieve the object key from the URL path
object_key = event["path"][1:]
# Retrieve the appropriate S3 bucket name based on the object key
bucket_name = get_bucket_name(object_key)
# Retrieve the object from S3
obj = s3.Object(bucket_name, object_key).get()
# Return the object's data
return {
"statusCode": 200,
"body": obj["Body"].read().decode('utf-8')
}
def get_bucket_name(object_key):
# Determine the appropriate S3 bucket to use based on the object key
# You can implement your own logic here
return ""
配置CloudFront分配为自定义起源,并将Lambda函数的ARN输入到“Origin Domain Name”字段中。
最后,将“Default Root Object”字段设置为Lambda函数负责的根对象的默认值,例如“index.html”。
这样,当CloudFront分配收到请求时,它将调用Lambda函数来检索适当的根对象并将其返回给客户端。