CloudFormation部署S3静态站+CloudFront:源站访问失败求助
问题排查与修复方案
核心错误点分析
1. CloudFront Origin配置错误
- OriginPath设置完全错误:你在
CloudFrontDistribution的Origin里写了OriginPath: /*,这会让CloudFront给所有请求路径强制加上/*前缀——比如用户访问/index.html,实际会转发到S3的/*/index.html,这种路径根本不存在,直接导致源站无法响应。 - Origin DomainName选错了:用S3静态网站托管时,CloudFront的Origin必须指向S3的静态网站专属Endpoint(格式是
bucket-name.s3-website-<你的区域>.amazonaws.com),而不是默认的S3对象存储Endpoint(bucket-name.s3.amazonaws.com)。后者是API接口,不支持静态网站的index自动跳转、自定义404这类特性。
2. S3 Bucket Policy权限逻辑错误
- Principal和Condition完全用错:你当前用
Service: cloudfront.amazonaws.com作为授权主体,还加了aws:Referer条件,这是典型的用法错误:- CloudFront访问私有S3桶,必须用**Origin Access Identity(OAI)或者Origin Access Control(OAC)**作为授权对象,不能直接给CloudFront服务开权限。
aws:Referer条件对CloudFront到S3的请求完全无效——CloudFront转发请求时不会带这个头,直接导致S3拒绝所有CloudFront的请求,这就是CloudFront提示Failed to contact the origin的根本原因。
3. 静态网站托管特性未被正确利用
虽然你配置了S3的WebsiteConfiguration,但因为Origin指向错误的Endpoint,CloudFront根本没法用到S3静态网站的index文档自动匹配等功能,进一步加重了访问错误。
修正后的关键配置代码
1. 新增CloudFront Origin Access Identity(OAI)
在Resources里添加这个资源,用来做CloudFront和S3之间的身份授权:
CloudFrontOAI: Type: AWS::CloudFront::CloudFrontOriginAccessIdentity Properties: CloudFrontOriginAccessIdentityConfig: Comment: OAI for private S3 bucket access
2. 修正CloudFront Distribution配置
- 替换Origin的DomainName为S3静态网站Endpoint(把
<你的区域>换成实际桶所在区域,比如us-east-1) - 删除错误的
OriginPath配置 - 把OAI关联到S3 Origin上:
CloudFrontDistribution: Type: AWS::CloudFront::Distribution DependsOn: - AppBucket - DefaultCachePolicy - CloudFrontOAI Properties: DistributionConfig: Enabled: true Origins: - Id: AppBucket DomainName: !Sub '${AppBucket}.s3-website-<你的区域>.amazonaws.com' S3OriginConfig: OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/${CloudFrontOAI}' DefaultCacheBehavior: ViewerProtocolPolicy: redirect-to-https TargetOriginId: AppBucket CachePolicyId: !Ref DefaultCachePolicy
3. 修正S3 Bucket Policy
改成允许OAI访问桶内所有对象,去掉没用的Referer条件:
BucketPolicy: Type: 'AWS::S3::BucketPolicy' DependsOn: - AppBucket - CloudFrontDistribution - CloudFrontOAI Properties: Bucket: !Ref AppBucket PolicyDocument: Id: MyPolicy Version: '2012-10-17' Statement: - Sid: PolicyForCloudFrontPrivateContent Action: s3:GetObject Effect: Allow Principal: AWS: !Sub 'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${CloudFrontOAI}' Resource: !Sub arn:aws:s3:::${AppBucket}/*
验证步骤
- 用修正后的模板重新部署CloudFormation
- 等CloudFront分发完成部署(一般5-10分钟)
- 访问CloudFront域名或自定义域名,确认能正常加载静态页面
- 直接访问S3网站URL,确认依然返回403(符合你的预期)
内容的提问来源于stack exchange,提问作者fudo
相关产品推荐
相关产品推荐

