如何通过CloudFormation将自定义域名关联至多区域API Gateway?
问题原因与解决方案
错误原因
AWS API Gateway的AWS::ApiGateway::DomainName资源属于全局命名空间,同一个域名(如example.com)无法在多个AWS区域重复创建,这就是第二个区域部署栈时提示The domain name you provided already exists的核心原因。
解决步骤
要实现同一域名关联多区域API Gateway,需要调整自定义域名策略并配置Route53多区域路由,具体如下:
1. 修改CloudFormation模板:每个区域使用独立子域名
将每个区域的API Gateway自定义域名改为带区域标识的子域名(避免全局冲突),同时配置对应区域的证书和子域名解析记录。
修改后的模板示例:
Resources: # 每个区域创建对应子域名的ACM证书(或通配符证书) MyCertificate: Type: "AWS::CertificateManager::Certificate" Properties: DomainName: !Sub "${aws_region}.example.com" ValidationMethod: DNS DomainValidationOptions: - DomainName: !Sub "${aws_region}.example.com" HostedZoneId: !Ref customDomain # 引用托管区ID,避免硬编码 # 区域唯一的API Gateway自定义域名 RegionalDomainName: Type: AWS::ApiGateway::DomainName Properties: RegionalCertificateArn: !Ref MyCertificate DomainName: !Sub "${aws_region}.example.com" EndpointConfiguration: Types: REGIONAL # 子域名解析到对应区域的API Gateway RegionalDomainRecord: Type: AWS::Route53::RecordSet Properties: HostedZoneId: !Ref customDomain Name: !Sub "${aws_region}.example.com" Type: A AliasTarget: DNSName: !GetAtt RegionalDomainName.RegionalDomainName HostedZoneId: !GetAtt RegionalDomainName.RegionalHostedZoneId # 关联API与自定义域名 MyApiMapping: Type: AWS::ApiGateway::BasePathMapping Properties: DomainName: !Ref RegionalDomainName RestApiId: !Ref MyApi Stage: prod # 替换为你的API部署阶段 MyApi: Type: AWS::Serverless::Api Properties: StageName: prod # 其他API配置项
2. 配置主域名的多区域路由
在Route53托管区example.com下创建加权/延迟路由策略的解析记录,将主域名example.com流量分发到两个区域的子域名。
可以单独创建一个全局CloudFormation栈(建议部署在us-east-1)来管理主域名路由:
Resources: # 东海岸区域路由记录 GlobalDomainRecordEast: Type: AWS::Route53::RecordSet Properties: HostedZoneId: !Ref customDomain Name: 'example.com' Type: A SetIdentifier: 'us-east-1' Weight: 50 # 权重可根据业务需求调整 AliasTarget: DNSName: 'us-east-1.example.com' HostedZoneId: !Ref customDomain # 西海岸区域路由记录 GlobalDomainRecordWest: Type: AWS::Route53::RecordSet Properties: HostedZoneId: !Ref customDomain Name: 'example.com' Type: A SetIdentifier: 'us-west-1' Weight: 50 AliasTarget: DNSName: 'us-west-1.example.com' HostedZoneId: !Ref customDomain
关键注意事项
- ACM证书是区域资源,每个区域的API Gateway需要对应区域的证书(可以申请通配符
*.example.com,每个区域单独创建)。 - 路由策略选择:加权路由适合流量拆分测试,延迟路由适合让用户访问最近的区域,根据业务需求调整。
- 确保
BasePathMapping关联的API阶段已部署,否则域名无法正常访问API。
内容的提问来源于stack exchange,提问作者ozil
相关产品推荐
相关产品推荐

