AWS CDK创建CloudFront分发报错:仅允许一个默认行为
CloudFront分发默认行为配置错误修复
问题场景
你通过CDK批量创建CloudFront分发,希望给monkey-ops子域名的分发添加CloudFront函数认证,但执行时触发报错。
错误信息(翻译后)
错误: 所有源中只能存在一个默认行为。[ 每个分发一个默认行为 ]。 在 new CloudFrontWebDistribution (D:\MonkeySource\2-Cloud\cdk_stacks\node_modules\aws-cdk-lib\aws-cloudfront\lib\web-distribution.js:1:6631) 在 new StaticSite (D:\MonkeySource\2-Cloud\cdk_stacks\lib\factory\static-site\static-site-factory.ts:120:42) 在 new SnWebStack (D:\MonkeySource\2-Cloud\cdk_stacks\lib\sn-web-stack.ts:57:7) 在 Object.<anonymous> (D:\MonkeySource\2-Cloud\cdk_stacks\bin\cdk.ts:19:1) 在 Module._compile (node:internal/modules/cjs/loader:1101:14) 在 Module.m._compile (D:\MonkeySource\2-Cloud\cdk_stacks\node_modules\ts-node\src\index.ts:1056:23) 在 Module._extensions..js (node:internal/modules/cjs/loader:1153:10) 在 Object.require.extensions.<computed> [as .ts] (D:\MonkeySource\2-Cloud\cdk_stacks\node_modules\ts-node\src\index.ts:1059:12) 在 Module.load (node:internal/modules/cjs/loader:981:32) 在 Function.Module._load (node:internal/modules/cjs/loader:822:12) 子进程退出,错误码 1
错误原因
问题出在monkey-ops分支的代码中:你将behavior的isDefaultBehavior设为了false,但CloudFront要求每个分发必须有且仅有一个默认行为(isDefaultBehavior: true),没有默认行为的分发配置是不合法的。
修复代码
修改monkey-ops分支的逻辑,在默认行为上直接添加函数关联,保持isDefaultBehavior为true:
// 1. 默认行为初始化 let behavior: cloudfront.Behavior = {isDefaultBehavior: true}; // Lambda Edge / Cloudfront Function Authentication... if (subDomain == "monkey-ops") { // 2. 创建Cloudfront Function const cfFunct = new cloudfront.Function(this, 'id', { functionName: 'http-auth-ops', comment: 'http-auth for monkey-ops.monkeytronics.co.nz static site', code: cloudfront.FunctionCode.fromFile({filePath: __dirname + '\\http-auth-ops-cf.js'}) }); // 保留默认行为,添加函数关联 behavior = { isDefaultBehavior: true, functionAssociations: [{ eventType: cloudfront.FunctionEventType.VIEWER_REQUEST, function: cfFunct }] }; } else { behavior = {isDefaultBehavior: true}; } let cloudFrontDistribution = new cloudfront.CloudFrontWebDistribution(this, subDomain + 'Distribution', { originConfigs: [ { customOriginSource: { domainName: s3Bucket.bucketWebsiteDomainName, originProtocolPolicy: cloudfront.OriginProtocolPolicy.HTTP_ONLY, }, behaviors : [ behavior ], } ], viewerCertificate: cloudfront.ViewerCertificate.fromAcmCertificate( tslCert, { aliases: [ subDomain + '.monkeytronics.co.nz' ], securityPolicy: cloudfront.SecurityPolicyProtocol.TLS_V1_2_2021, sslMethod: cloudfront.SSLMethod.SNI, }, ), });
关键说明
- 默认行为是CloudFront分发的强制要求,用于处理所有未被其他路径规则匹配的请求
- 如果需要添加非默认行为(比如匹配特定URL路径的规则),可以在
behaviors数组中追加,但必须保证始终有一个isDefaultBehavior: true的项存在
内容的提问来源于stack exchange,提问作者monkey
相关产品推荐
相关产品推荐

