Please see below, in case if anyone is facing this issue when using API Gateway as a secondary origin - behavior instead of default behavior for the Cloudfront Distribution i.e.
- forwarding all paths like
/api/*
requests to API Gateway
- serving the remaining paths with an
s3
or other default resource like an Application load balancer
I was using AWS CDK to define and deploy AWS API Gateway as a secondary behavior and faced the same issue and I did everything including
- forwarding headers and query params
- enabling all http request methods
- Setting the API gateway as regional
My configuration for the deployment is as follows:
originConfigs: [{
customOriginSource: {
domainName: clientAppBucket.bucketWebsiteDomainName,
originProtocolPolicy: cloudfront.OriginProtocolPolicy.HTTP_ONLY
},
behaviors: [{
isDefaultBehavior: true,
compress: true
}]
},
{
customOriginSource: { domainName: `${api.restApiId}.execute-api.${this.region}.amazonaws.com/prod` },
behaviors: [
{
pathPattern: "/api/*",
allowedMethods: cloudfront.CloudFrontAllowedMethods.ALL,
defaultTtl: cdk.Duration.seconds(0),
forwardedValues: {
queryString: true,
headers: ["Authorization"],
},
},
],
}]
The problem was that Cloudfront prepends the path that we are using as a custom behavior with each request i.e. when we call domain.com/api/something
, It will not call ${api.restApiId}.execute-api.${this.region}.amazonaws.com/
prod/something. Instead it will call ${api.restApiId}.execute-api.${this.region}.amazonaws.com
/prod/api/something.
Therefore, either the stage name of the default API Gateway URL which is usually prod
should be equal to the behavior path which we specify i.e /path/*
or /api/*
or /backend/*
etc -> /prod/*
or we should have a /path/
as a resource at the top level of RestApi and nest all the resources under it