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

配置CloudFront多源架构:限制API Gateway仅通过该CloudFront访问

限制API Gateway仅通过指定CloudFront分发访问的配置方案

针对你的架构(S3静态站与API Gateway共用同一CloudFront分发),以下是禁用API Gateway直接调用的具体步骤:

1. 给CloudFront配置自定义请求头

  • 打开CloudFront控制台,找到目标分发的行为列表,选中对应API Gateway源的行为条目并编辑
  • 在源请求策略区域,创建自定义源请求策略,添加一个自定义请求头(例如X-Allowed-CF-Dist),值设置为你的CloudFront分发ID(格式类似E1234567890AB)
  • 保存策略并关联到该行为,确保CloudFront向API Gateway转发这个自定义头

2. 为API Gateway设置资源策略

  • 进入API Gateway控制台,选择目标API,切换到资源策略标签页
  • 替换默认策略为以下JSON(替换占位符为你的实际信息):
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": "*",
      "Action": "execute-api:Invoke",
      "Resource": "arn:aws:execute-api:你的区域:你的账号ID:你的API ID/*/*/*",
      "Condition": {
        "StringEquals": {
          "execute-api:Header/X-Allowed-CF-Dist": "你的CloudFront分发ID"
        }
      }
    },
    {
      "Effect": "Deny",
      "Principal": "*",
      "Action": "execute-api:Invoke",
      "Resource": "arn:aws:execute-api:你的区域:你的账号ID:你的API ID/*/*/*",
      "Condition": {
        "Null": {
          "execute-api:Header/X-Allowed-CF-Dist": true
        }
      }
    }
  ]
}
  • 这个策略会拒绝所有未携带指定自定义头的请求,仅放行来自目标CloudFront分发的调用

3. 关闭API Gateway的直接访问端点(可选但推荐)

  • 若使用REST API:在API Gateway的设置页面,找到「默认端点」选项并关闭,仅保留通过CloudFront的访问路径
  • 若使用HTTP API:确保未配置任何独立的自定义域名,所有访问都通过CloudFront域名路由

4. 验证配置

  • 直接访问API Gateway的原生端点(如https://你的API ID.execute-api.你的区域.amazonaws.com/你的阶段),应返回403 Forbidden
  • 通过CloudFront域名访问API路径(如https://你的CloudFront域名/api/xxx),应能正常获取响应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 23:12:23