Context
I'm currently facing a weird problem from my cloudfront distribution.
It has two behaviors. Default behavior displays static content from a S3 Bucket. Additional behavior (/api/) is an endpoint to a dedicated HTTP Origin which is the website backend.
Here is the CDK code.
const distribution = new Distribution(this, `${this.constructPrefix}-cloudfront-${this.constructSuffix}`, {
defaultBehavior: {
origin: new S3Origin(bucket, {
originAccessIdentity: oai,
}),
functionAssociations: [
{
function: cloudfrontFunctionRewritePath,
eventType: FunctionEventType.VIEWER_REQUEST,
},
],
viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
cachePolicy: frontCachePolicy,
},
additionalBehaviors: {
"/api/*": {
origin: new HttpOrigin(`${buildConfig.ApiURL}`, {
httpsPort: 443,
protocolPolicy: OriginProtocolPolicy.HTTPS_ONLY,
customHeaders: {
"x-cloudfront-secret": `${cloudfrontSecret.secretValueFromJson("password")}`,
},
}),
cachePolicy: apiCachePolicy,
viewerProtocolPolicy: ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
allowedMethods: AllowedMethods.ALLOW_ALL,
edgeLambdas: edgeLambdaAssociations,
},
},
logBucket: bucketLog,
logFilePrefix: "cloudfront/",
enabled: true,
defaultRootObject: "index.html",
domainNames: [domainName],
certificate: secureCertificate,
errorResponses: [
{
httpStatus: 404,
responseHttpStatus: 200,
responsePagePath: "/index.html",
ttl: Duration.seconds(86400),
},
],
...(buildConfig.AWSWebAclArn !== "NONE" ? { webAclId: buildConfig.AWSWebAclArn } : {}),
});
The Problem
Right now, one of my API endpoint (/api/endpoint) on my Cloudfront distribution randomly returns a "no such key the specified key does not exist" with HTTP status code 404.
Every other API endpoint works well. What's weird is that the response has an header with "Server: AmazonS3".
It seems like Cloudfront tries to get "/api/endpoint" from its default behavior (bucket S3) instead of the additional one (/api/).
Please note that it seems to work most of the time. I can't quite understand why Cloudfront is behaving like that at times.
Please, do you have any idea ?