You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用aws_cloudfront将HttpApi设为CloudFront源并实现HTTP转HTTPS?

能否将API Gateway v2的HttpApi作为CloudFront分发的源?

可以实现,但不能直接使用RestApiOrigin——这个类是专门为API Gateway v1的REST API设计的,不适用于v2的HttpApi。你需要改用HttpOrigin来指向HttpApi的域名,并配合正确的配置完成集成。

实现步骤及代码示例

  1. 获取HttpApi的域名:通过HttpApi实例的api_domain_name属性获取完整域名(或从api.url中提取,注意去掉https://前缀)。
  2. 创建HttpOrigin源:用该域名初始化HttpOrigin,并配置必要的源请求策略,确保转发API Gateway需要的请求头(比如Host头)。
  3. 配置CloudFront分发:设置默认行为使用这个HttpOrigin,同时开启HTTP到HTTPS的重定向。

示例代码如下:

from aws_cdk import (
    aws_cloudfront as cloudfront,
    aws_cloudfront_origins as origins,
    aws_apigatewayv2_alpha as apigatewayv2,
    Stack,
)
from constructs import Construct

class MyStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # 假设你已经创建了HttpApi实例
        http_api = apigatewayv2.HttpApi(self, "MyHttpApi")

        # 获取HttpApi的域名(去掉https://前缀)
        api_domain = http_api.api_domain_name.domain_name

        # 创建CloudFront分发
        self.distribution = cloudfront.Distribution(
            self,
            "MyDistribution",
            default_behavior=cloudfront.BehaviorOptions(
                origin=origins.HttpOrigin(
                    domain_name=api_domain,
                    # 转发Host头,API Gateway需要这个来正确路由请求
                    origin_request_policy=cloudfront.OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER,
                ),
                # 强制将HTTP请求重定向到HTTPS
                viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
                allowed_methods=cloudfront.AllowedMethods.ALLOW_ALL,
            ),
            # 可选:设置默认根对象,根据你的API需求调整
            default_root_object="",
        )

关键注意事项

  • Origin Request Policy:必须确保转发必要的请求头,ALL_VIEWER_EXCEPT_HOST_HEADER是常用选择,它会转发除Host外的所有Viewer请求头,同时CloudFront会自动设置正确的Host头指向你的HttpApi域名。
  • Alpha模块兼容性:aws_apigatewayv2_alpha是实验性模块,使用时注意版本兼容性,后续正式发布后可能需要调整导入路径。
  • 域名验证:如果你的HttpApi使用了自定义域名,需要确保CloudFront的源配置指向正确的自定义域名,同时配置好对应的DNS解析和证书。

内容的提问来源于stack exchange,提问作者louisdeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:25:28