我在/
路径上使用 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'
})