You need to enable JavaScript to run this app. 如何使用AWS CDK为APIGateway配置并部署所需API映射设置?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用AWS CDK为APIGateway配置并部署所需API映射设置?

基于CDK为API Gateway REST API配置自定义域名映射的解决方案

你当前使用的apigateway.LambdaRestApi属于API Gateway V1版本的REST API资源,而apigatewayv2.ApiMapping是专为API Gateway V2版本的HTTP API、WebSocket API设计的组件,二者不兼容,这是你之前实现失败的核心原因。REST API的自定义域名映射不需要调用V2版本的组件,直接使用V1版本的内置能力即可实现。

场景1:根路径直接映射到API

你现有代码中已经在LambdaRestApi的domainName参数中完成了根域名的绑定配置,同时配套的Route53 A记录也已经配置完成,该配置可以正常生效,无需额外添加映射组件。

场景2:需要配置指定路径的映射(如your-domain.com/dyndns/*映射到当前API)

你需要将自定义域名配置从LambdaRestApi参数中抽离,单独创建DomainName资源后添加路径映射,修改后的代码示例如下:

// 1. 先创建REST API,暂不配置domainName参数
const restApi = new apigateway.LambdaRestApi(this, "dyndns-api", {
  handler: dyndnsLambda,
  proxy: false,
});

// 2. 单独创建自定义域名资源
const apiDomain = new apigateway.DomainName(this, "ApiDomain", {
  domainName: siteDomain,
  certificate: certificate,
  endpointType: apigateway.EndpointType.REGIONAL,
  securityPolicy: apigateway.SecurityPolicy.TLS_1_2,
});

// 3. 添加路径映射,这里path参数填你需要的路径前缀,填''代表根路径
apiDomain.addBasePathMapping(restApi, {
  basePath: 'dyndns', // 按需修改,留空则为根路径映射
});

// 4. Route53记录保持不变,target指向自定义域名即可
new route53.ARecord(this, "apiDNS", {
  zone: zone,
  recordName: siteDomain,
  target: route53.RecordTarget.fromAlias(new route53Targets.ApiGatewayDomain(apiDomain)),
});

// 剩余的MethodResponse、IntegrationResponse、Lambda集成、方法添加等原有代码保持不变
const methodResponse: apigateway.MethodResponse = {
  statusCode: "200", 
  responseModels: {"application/json": apigateway.Model.EMPTY_MODEL}
}

const integrationResponse: apigateway.IntegrationResponse = {
  statusCode: "200",
  contentHandling: apigateway.ContentHandling.CONVERT_TO_TEXT
}

const requestTemplate = {
  "execution_mode" : "$input.params('mode')",
  "source_ip" : "$context.identity.sourceIp",
  "set_hostname" : "$input.params('hostname')",
  "validation_hash" : "$input.params('hash')"
}

const dnydnsIntegration = new apigateway.LambdaIntegration(dyndnsLambda, {
  allowTestInvoke: true,
  proxy: false,
  integrationResponses: [integrationResponse],
  passthroughBehavior: apigateway.PassthroughBehavior.WHEN_NO_TEMPLATES,
  requestTemplates: { "application/json": JSON.stringify(requestTemplate) },
});

restApi.root.addMethod("GET", dnydnsIntegration, {
  methodResponses: [methodResponse]
});

如果你需要同一个自定义域名映射多个不同的REST API,只需要重复调用addBasePathMapping方法,给每个API分配不同的basePath前缀即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 02:33:04