0

我在/路径上使用 s3 和 cloudfront 为静态网站提供服务。

我想/api/*从 HTTP API 服务。

我的静态网站已使用 cloudfront 正确配置。而且我还使用 cdk 将自定义域配置为 HTTP api

但是当我尝试访问我的 http API 时,我得到 404 not found 响应。基本上 Cloudfront 不会将我的/api/*请求转发到 HTTP API。

这是我的云端 CDK 代码

const distribution = new CloudFrontWebDistribution(this, 'CloudfrontWebDistribution', {
      httpVersion: HttpVersion.HTTP2,
      priceClass: PriceClass.PRICE_CLASS_ALL,
      viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
      originConfigs: [
        {
          s3OriginSource: {
            s3BucketSource: bucket,
            originAccessIdentity
          },
          behaviors: [{
              isDefaultBehavior: true,
              defaultTtl: Duration.hours(1)
            }]
        }, 
        {
          customOriginSource: {
            domainName: website_domain
          },
          behaviors: [{
            pathPattern: '/api/*',
            isDefaultBehavior: false,
            allowedMethods: CloudFrontAllowedMethods.ALL,
            defaultTtl: Duration.seconds(0),
            minTtl: Duration.seconds(0),
            maxTtl: Duration.seconds(0),
            forwardedValues: {
              queryString: true,
              cookies: {
                forward: 'all'
              }
            }
          }]
        }
      ],
      errorConfigurations: [
        {
          errorCode: 404,
          responseCode: 404,
          responsePagePath: '/404.html'
        }
      ],
      viewerCertificate: ViewerCertificate.fromAcmCertificate(certificate, {
        aliases: [website_domain],
        securityPolicy: SecurityPolicyProtocol.TLS_V1_2_2018
      })
    })

这不是必需的,但我还提供了我的 HTTP API 自定义域 CDK 代码

    const certificate = Certificate.fromCertificateArn(this, 'ssl_cert', certArn)
    
    const domain = new DomainName(this, 'domain', {
      domainName: website_domain,
      certificate
    }) 

    const api = new HttpApi(this, 'endpoint', {
      defaultDomainMapping: {
        domainName: domain,
        mappingKey: 'api'
      },
      corsPreflight: {
        allowCredentials: true,
        allowHeaders: ['Content-Type'],
        allowMethods: [HttpMethod.GET, HttpMethod.POST, HttpMethod.OPTIONS, HttpMethod.HEAD],
        allowOrigins: [
          "https://cdn.ampproject.org",
          "https://www.bing-amp.com"
        ]
      },
      apiName: 'myAPI'
    })
4

1 回答 1

0

我没有在代码片段中看到您对 HttpApi 的路由定义,但我怀疑问题在于它们不是以/api.

CloudFront 中的pathPattern行为只是为了匹配 url 并路由到适当的源。但 CloudFront 不会将其从转发到源的路径中删除。

我知道有两种解决方案

  • 在所有路线前面添加/api路径段
  • 在调用原点之前使用 lambda@edge 删除路径段。

对于第二个选项,请参阅此处接受的答案: Multiple Cloudfront Origins with Behavior Path Redirection

于 2020-08-31T18:49:27.837 回答