Cloudfront 分发无法在一个堆栈中加载子目录,但在另一个堆栈中工作



我正在使用 cloudformation(通过无服务器框架)将静态站点部署到 S3,并设置一个别名来自 route53 域的 cloudfront 分配。

我将其用于两个域,每个域都是在 route53 中创建的新域。我正在尝试使用从现有注册商转移到 route53 的旧域进行相同的设置。

此新域的 Cloudfront 分配无法加载子目录。即https://[mydistid].cloudfront.net/sub/dir/不会在https://[mydistid].cloudfront.net/sub/dir/index.html加载资源

其他 SO 问题中涵盖了一个常见的问题。您必须将 s3 存储桶指定为自定义源,CloudFront 才能将默认根对象应用于子目录。

我已经这样做了,从我的serverless.yml CloudFrontDistribution资源中可以看出:


XxxxCloudFrontDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Aliases:
- ${self:provider.environment.CUSTOM_DOMAIN}
Origins:
- DomainName: ${self:provider.environment.BUCKET_NAME}.s3.amazonaws.com
Id: Xxxx
CustomOriginConfig:
HTTPPort: 80
HTTPSPort: 443
OriginProtocolPolicy: https-only
Enabled: 'true'
DefaultRootObject: index.html
CustomErrorResponses:
- ErrorCode: 404
ResponseCode: 200
ResponsePagePath: /error.html
DefaultCacheBehavior:
AllowedMethods:
- DELETE
- GET
- HEAD
- OPTIONS
- PATCH
- POST
- PUT
TargetOriginId: Xxxx
Compress: 'true'
ForwardedValues:
QueryString: 'false'
Cookies:
Forward: none
ViewerProtocolPolicy: redirect-to-https
ViewerCertificate:
AcmCertificateArn: ${self:provider.environment.ACM_CERT_ARN}
SslSupportMethod: sni-only

这会导致 CF 分配将 s3 存储桶作为 AWS 中的"自定义源"。

但是,当访问子目录时,将路由到错误页面,而不是该目录中的默认根对象。

非常奇怪的是,它使用与另一个没问题的堆栈相同的配置。到目前为止,我能看到的唯一差异是工作堆栈有一个 route53 创建的域,而它使用源自另一个注册商的域,所以我会看到名称服务器迁移完成后会发生什么。我怀疑这会解决问题,因为 CF 发行版不应受到 route53 域状态的影响

我现在有两个堆栈都可以工作。问题是使用了 S3 REST API URL

${self:provider.environment.BUCKET_NAME}.s3.amazonaws.com

将两者更改为 s3 网站 url 有效:

${self:provider.environment.BUCKET_NAME}.s3-website-us-east-1.amazonaws.com

我没有解释为什么以前的 URL 适用于 1 个堆栈而不是另一个堆栈。

我需要做的另一个更改是将CustomOriginConfigOriginProtocolPolicy设置为http-only,这是因为 s3 网站不支持 https。

这是我更新的CloudFormation配置:

XxxxCloudFrontDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Aliases:
- ${self:provider.environment.CUSTOM_DOMAIN}
Origins:
- DomainName: ${self:provider.environment.BUCKET_NAME}.s3-website-us-east-1.amazonaws.com
Id: Xxxx
CustomOriginConfig:
HTTPPort: 80
OriginProtocolPolicy: http-only
Enabled: 'true'
DefaultRootObject: index.html
CustomErrorResponses:
- ErrorCode: 404
ResponseCode: 200
ResponsePagePath: /error.html
DefaultCacheBehavior:
AllowedMethods:
- DELETE
- GET
- HEAD
- OPTIONS
- PATCH
- POST
- PUT
TargetOriginId: Xxxx
Compress: 'true'
ForwardedValues:
QueryString: 'false'
Cookies:
Forward: none
ViewerProtocolPolicy: redirect-to-https
ViewerCertificate:
AcmCertificateArn: ${self:provider.environment.ACM_CERT_ARN}
SslSupportMethod: sni-only

最新更新