Amazon CloudFront Construct Library
Amazon CloudFront is a web service that speeds up distribution of your static and dynamic web content, such as .html, .css, .js, and image files, to your users. CloudFront delivers your content through a worldwide network of data centers called edge locations. When a user requests content that you're serving with CloudFront, the user is routed to the edge location that provides the lowest latency, so that content is delivered with the best possible performance.
Distribution API
The Distribution API replaces the CloudFrontWebDistribution API which is now deprecated. The Distribution API is optimized for the most common use cases of CloudFront distributions (e.g., single origin and behavior, few customizations) while still providing the ability for more advanced use cases. The API focuses on simplicity for the common use cases, and convenience methods for creating the behaviors and origins necessary for more complex use cases.
Creating a distribution
CloudFront distributions deliver your content from one or more origins; an origin is the location where you store the original version of your content. Origins can be created from S3 buckets or a custom origin (HTTP server). Constructs to define origins are in the aws-cdk-lib/aws-cloudfront-origins module.
Each distribution has a default behavior which applies to all requests to that distribution, and routes requests to a primary origin. Additional behaviors may be specified for an origin with a given URL path pattern. Behaviors allow routing with multiple origins, controlling which HTTP methods to support, whether to require users to use HTTPS, and what query strings or cookies to forward to your origin, among other settings.
From an S3 Bucket
An S3 bucket can be added as an origin. An S3 bucket origin can either be configured as a standard bucket or as a website endpoint (see AWS docs for Using an S3 Bucket).
// Creates a distribution from an S3 bucket with origin access control
const myBucket = new s3.Bucket(this, 'myBucket');
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: {
origin: origins.S3BucketOrigin.withOriginAccessControl(myBucket) // Automatically creates a S3OriginAccessControl construct
},
});
# Creates a distribution from an S3 bucket with origin access control
my_bucket = s3.Bucket(self, "myBucket")
cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.S3BucketOrigin.with_origin_access_control(my_bucket)
)
)
// Creates a distribution from an S3 bucket with origin access control
Bucket myBucket = new Bucket(this, "myBucket");
Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder()
.origin(S3BucketOrigin.withOriginAccessControl(myBucket))
.build())
.build();
// Creates a distribution from an S3 bucket with origin access control
var myBucket = new Bucket(this, "myBucket");
new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = S3BucketOrigin.WithOriginAccessControl(myBucket)
}
});
// Creates a distribution from an S3 bucket with origin access control
myBucket := s3.NewBucket(this, jsii.String("myBucket"))
cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.S3BucketOrigin_WithOriginAccessControl(myBucket),
},
})
See the README of the aws-cdk-lib/aws-cloudfront-origins module for more information on setting up S3 origins and origin access control (OAC).
ELBv2 Load Balancer
An Elastic Load Balancing (ELB) v2 load balancer may be used as an origin. In order for a load balancer to serve as an origin, it must be publicly accessible (internetFacing is true). Both Application and Network load balancers are supported.
// Creates a distribution from an ELBv2 load balancer
declare const vpc: ec2.Vpc;
// Create an application load balancer in a VPC. 'internetFacing' must be 'true'
// for CloudFront to access the load balancer and use it as an origin.
const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', {
vpc,
internetFacing: true,
});
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.LoadBalancerV2Origin(lb) },
});
# Creates a distribution from an ELBv2 load balancer
# vpc: ec2.Vpc
# Create an application load balancer in a VPC. 'internetFacing' must be 'true'
# for CloudFront to access the load balancer and use it as an origin.
lb = elbv2.ApplicationLoadBalancer(self, "LB",
vpc=vpc,
internet_facing=True
)
cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(origin=origins.LoadBalancerV2Origin(lb))
)
// Creates a distribution from an ELBv2 load balancer
Vpc vpc;
// Create an application load balancer in a VPC. 'internetFacing' must be 'true'
// for CloudFront to access the load balancer and use it as an origin.
ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB")
.vpc(vpc)
.internetFacing(true)
.build();
Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder().origin(new LoadBalancerV2Origin(lb)).build())
.build();
// Creates a distribution from an ELBv2 load balancer
Vpc vpc;
// Create an application load balancer in a VPC. 'internetFacing' must be 'true'
// for CloudFront to access the load balancer and use it as an origin.
var lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps {
Vpc = vpc,
InternetFacing = true
});
new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions { Origin = new LoadBalancerV2Origin(lb) }
});
// Creates a distribution from an ELBv2 load balancer
var vpc Vpc
// Create an application load balancer in a VPC. 'internetFacing' must be 'true'
// for CloudFront to access the load balancer and use it as an origin.
lb := elbv2.NewApplicationLoadBalancer(this, jsii.String("LB"), &ApplicationLoadBalancerProps{
Vpc: Vpc,
InternetFacing: jsii.Boolean(true),
})
cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewLoadBalancerV2Origin(lb),
},
})
From an HTTP endpoint
Origins can also be created from any other HTTP endpoint, given the domain name, and optionally, other origin properties.
// Creates a distribution from an HTTP endpoint
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.HttpOrigin('www.example.com') },
});
# Creates a distribution from an HTTP endpoint
cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(origin=origins.HttpOrigin("www.example.com"))
)
// Creates a distribution from an HTTP endpoint
// Creates a distribution from an HTTP endpoint
Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder().origin(new HttpOrigin("www.example.com")).build())
.build();
// Creates a distribution from an HTTP endpoint
// Creates a distribution from an HTTP endpoint
new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions { Origin = new HttpOrigin("www.example.com") }
});
// Creates a distribution from an HTTP endpoint
// Creates a distribution from an HTTP endpoint
cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewHttpOrigin(jsii.String("www.example.com")),
},
})
CloudFront SaaS Manager resources
Multi-tenant distribution and tenant providing ACM certificates
You can use Cloudfront to build multi-tenant distributions to house applications.
To create a multi-tenant distribution w/parameters, create a Distribution construct, and then update DistributionConfig in the CfnDistribution to use connectionMode: "tenant-only"
Then create a tenant
// Create the simple Origin
const myBucket = new s3.Bucket(this, 'myBucket');
const s3Origin = origins.S3BucketOrigin.withOriginAccessControl(myBucket, {
originAccessLevels: [cloudfront.AccessLevel.READ, cloudfront.AccessLevel.LIST],
});
// Create the Distribution construct
const myMultiTenantDistribution = new cloudfront.Distribution(this, 'distribution', {
defaultBehavior: {
origin: s3Origin,
},
defaultRootObject: 'index.html', // recommended to specify
});
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
const cfnDistribution = myMultiTenantDistribution.node.defaultChild as cloudfront.CfnDistribution;
const defaultCacheBehavior: cloudfront.CfnDistribution.DefaultCacheBehaviorProperty = {
targetOriginId: myBucket.bucketArn,
viewerProtocolPolicy: 'allow-all',
compress: false,
allowedMethods: ['GET', 'HEAD'],
cachePolicyId: cloudfront.CachePolicy.CACHING_OPTIMIZED.cachePolicyId
};
// Create the updated distributionConfig
const distributionConfig: cloudfront.CfnDistribution.DistributionConfigProperty = {
defaultCacheBehavior: defaultCacheBehavior,
enabled: true,
// the properties below are optional
connectionMode: 'tenant-only',
origins: [
{
id: myBucket.bucketArn,
domainName: myBucket.bucketDomainName,
s3OriginConfig: {},
originPath: "/{{tenantName}}"
},
],
tenantConfig: {
parameterDefinitions: [
{
definition: {
stringSchema: {
required: false,
// the properties below are optional
comment: 'tenantName',
defaultValue: 'root',
},
},
name: 'tenantName',
},
],
},
};
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.distributionConfig = distributionConfig;
// Create a distribution tenant using an existing ACM certificate
const cfnDistributionTenant = new cloudfront.CfnDistributionTenant(this, 'distribution-tenant', {
distributionId: myMultiTenantDistribution.distributionId,
domains: ['my-tenant.my.domain.com'],
name: 'my-tenant',
enabled: true,
parameters: [ // Override the default 'tenantName' parameter (root) defined in the multi-tenant distribution.
{
name: 'tenantName',
value: 'app',
},
],
customizations: {
certificate: {
arn: 'REPLACE_WITH_ARN', // Certificate must be in us-east-1 region and cover 'my-tenant.my.domain.com'
},
},
});
# Create the simple Origin
my_bucket = s3.Bucket(self, "myBucket")
s3_origin = origins.S3BucketOrigin.with_origin_access_control(my_bucket,
origin_access_levels=[cloudfront.AccessLevel.READ, cloudfront.AccessLevel.LIST]
)
# Create the Distribution construct
my_multi_tenant_distribution = cloudfront.Distribution(self, "distribution",
default_behavior=cloudfront.BehaviorOptions(
origin=s3_origin
),
default_root_object="index.html"
)
# Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
cfn_distribution = my_multi_tenant_distribution.node.default_child
default_cache_behavior = cloudfront.CfnDistribution.DefaultCacheBehaviorProperty(
target_origin_id=my_bucket.bucket_arn,
viewer_protocol_policy="allow-all",
compress=False,
allowed_methods=["GET", "HEAD"],
cache_policy_id=cloudfront.CachePolicy.CACHING_OPTIMIZED.cache_policy_id
)
# Create the updated distributionConfig
distribution_config = cloudfront.CfnDistribution.DistributionConfigProperty(
default_cache_behavior=default_cache_behavior,
enabled=True,
# the properties below are optional
connection_mode="tenant-only",
origins=[cloudfront.CfnDistribution.OriginProperty(
id=my_bucket.bucket_arn,
domain_name=my_bucket.bucket_domain_name,
s3_origin_config=cloudfront.CfnDistribution.S3OriginConfigProperty(),
origin_path="/{{tenantName}}"
)
],
tenant_config=cloudfront.CfnDistribution.TenantConfigProperty(
parameter_definitions=[cloudfront.CfnDistribution.ParameterDefinitionProperty(
definition=cloudfront.CfnDistribution.DefinitionProperty(
string_schema=cloudfront.CfnDistribution.StringSchemaProperty(
required=False,
# the properties below are optional
comment="tenantName",
default_value="root"
)
),
name="tenantName"
)
]
)
)
# Override the distribution configuration to enable multi-tenancy.
cfn_distribution.distribution_config = distribution_config
# Create a distribution tenant using an existing ACM certificate
cfn_distribution_tenant = cloudfront.CfnDistributionTenant(self, "distribution-tenant",
distribution_id=my_multi_tenant_distribution.distribution_id,
domains=["my-tenant.my.domain.com"],
name="my-tenant",
enabled=True,
parameters=[cloudfront.CfnDistributionTenant.ParameterProperty(
name="tenantName",
value="app"
)],
customizations=cloudfront.CfnDistributionTenant.CustomizationsProperty(
certificate=cloudfront.CfnDistributionTenant.CertificateProperty(
arn="REPLACE_WITH_ARN"
)
)
)
// Create the simple Origin
Bucket myBucket = new Bucket(this, "myBucket");
IOrigin s3Origin = S3BucketOrigin.withOriginAccessControl(myBucket, S3BucketOriginWithOACProps.builder()
.originAccessLevels(List.of(AccessLevel.READ, AccessLevel.LIST))
.build());
// Create the Distribution construct
Distribution myMultiTenantDistribution = Distribution.Builder.create(this, "distribution")
.defaultBehavior(BehaviorOptions.builder()
.origin(s3Origin)
.build())
.defaultRootObject("index.html")
.build();
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
CfnDistribution cfnDistribution = (CfnDistribution)myMultiTenantDistribution.getNode().getDefaultChild();
DefaultCacheBehaviorProperty defaultCacheBehavior = DefaultCacheBehaviorProperty.builder()
.targetOriginId(myBucket.getBucketArn())
.viewerProtocolPolicy("allow-all")
.compress(false)
.allowedMethods(List.of("GET", "HEAD"))
.cachePolicyId(CachePolicy.CACHING_OPTIMIZED.getCachePolicyId())
.build();
// Create the updated distributionConfig
DistributionConfigProperty distributionConfig = DistributionConfigProperty.builder()
.defaultCacheBehavior(defaultCacheBehavior)
.enabled(true)
// the properties below are optional
.connectionMode("tenant-only")
.origins(List.of(OriginProperty.builder()
.id(myBucket.getBucketArn())
.domainName(myBucket.getBucketDomainName())
.s3OriginConfig(S3OriginConfigProperty.builder().build())
.originPath("/{{tenantName}}")
.build()))
.tenantConfig(TenantConfigProperty.builder()
.parameterDefinitions(List.of(ParameterDefinitionProperty.builder()
.definition(DefinitionProperty.builder()
.stringSchema(StringSchemaProperty.builder()
.required(false)
// the properties below are optional
.comment("tenantName")
.defaultValue("root")
.build())
.build())
.name("tenantName")
.build()))
.build())
.build();
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.getDistributionConfig() = distributionConfig;
// Create a distribution tenant using an existing ACM certificate
CfnDistributionTenant cfnDistributionTenant = CfnDistributionTenant.Builder.create(this, "distribution-tenant")
.distributionId(myMultiTenantDistribution.getDistributionId())
.domains(List.of("my-tenant.my.domain.com"))
.name("my-tenant")
.enabled(true)
.parameters(List.of(ParameterProperty.builder()
.name("tenantName")
.value("app")
.build()))
.customizations(CustomizationsProperty.builder()
.certificate(CertificateProperty.builder()
.arn("REPLACE_WITH_ARN")
.build())
.build())
.build();
// Create the simple Origin
var myBucket = new Bucket(this, "myBucket");
var s3Origin = S3BucketOrigin.WithOriginAccessControl(myBucket, new S3BucketOriginWithOACProps {
OriginAccessLevels = new [] { AccessLevel.READ, AccessLevel.LIST }
});
// Create the Distribution construct
var myMultiTenantDistribution = new Distribution(this, "distribution", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = s3Origin
},
DefaultRootObject = "index.html"
});
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
var cfnDistribution = (CfnDistribution)myMultiTenantDistribution.Node.DefaultChild;
var defaultCacheBehavior = new DefaultCacheBehaviorProperty {
TargetOriginId = myBucket.BucketArn,
ViewerProtocolPolicy = "allow-all",
Compress = false,
AllowedMethods = new [] { "GET", "HEAD" },
CachePolicyId = CachePolicy.CACHING_OPTIMIZED.CachePolicyId
};
// Create the updated distributionConfig
var distributionConfig = new DistributionConfigProperty {
DefaultCacheBehavior = defaultCacheBehavior,
Enabled = true,
// the properties below are optional
ConnectionMode = "tenant-only",
Origins = new [] { new OriginProperty {
Id = myBucket.BucketArn,
DomainName = myBucket.BucketDomainName,
S3OriginConfig = new S3OriginConfigProperty { },
OriginPath = "/{{tenantName}}"
} },
TenantConfig = new TenantConfigProperty {
ParameterDefinitions = new [] { new ParameterDefinitionProperty {
Definition = new DefinitionProperty {
StringSchema = new StringSchemaProperty {
Required = false,
// the properties below are optional
Comment = "tenantName",
DefaultValue = "root"
}
},
Name = "tenantName"
} }
}
};
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.DistributionConfig = distributionConfig;
// Create a distribution tenant using an existing ACM certificate
var cfnDistributionTenant = new CfnDistributionTenant(this, "distribution-tenant", new CfnDistributionTenantProps {
DistributionId = myMultiTenantDistribution.DistributionId,
Domains = new [] { "my-tenant.my.domain.com" },
Name = "my-tenant",
Enabled = true,
Parameters = new [] { new ParameterProperty {
Name = "tenantName",
Value = "app"
} },
Customizations = new CustomizationsProperty {
Certificate = new CertificateProperty {
Arn = "REPLACE_WITH_ARN"
}
}
});
// Create the simple Origin
myBucket := s3.NewBucket(this, jsii.String("myBucket"))
s3Origin := origins.S3BucketOrigin_WithOriginAccessControl(myBucket, &S3BucketOriginWithOACProps{
OriginAccessLevels: []AccessLevel{
cloudfront.AccessLevel_READ,
cloudfront.AccessLevel_LIST,
},
})
// Create the Distribution construct
myMultiTenantDistribution := cloudfront.NewDistribution(this, jsii.String("distribution"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: s3Origin,
},
DefaultRootObject: jsii.String("index.html"),
})
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
cfnDistribution := myMultiTenantDistribution.Node.defaultChild.(CfnDistribution)
defaultCacheBehavior := &DefaultCacheBehaviorProperty{
TargetOriginId: myBucket.bucketArn,
ViewerProtocolPolicy: jsii.String("allow-all"),
Compress: jsii.Boolean(false),
AllowedMethods: []*string{
jsii.String("GET"),
jsii.String("HEAD"),
},
CachePolicyId: cloudfront.CachePolicy_CACHING_OPTIMIZED().CachePolicyId,
}
// Create the updated distributionConfig
distributionConfig := &DistributionConfigProperty{
DefaultCacheBehavior: defaultCacheBehavior,
Enabled: jsii.Boolean(true),
// the properties below are optional
ConnectionMode: jsii.String("tenant-only"),
Origins: []interface{}{
&OriginProperty{
Id: myBucket.bucketArn,
DomainName: myBucket.BucketDomainName,
S3OriginConfig: &S3OriginConfigProperty{
},
OriginPath: jsii.String("/{{tenantName}}"),
},
},
TenantConfig: &TenantConfigProperty{
ParameterDefinitions: []interface{}{
&ParameterDefinitionProperty{
Definition: &DefinitionProperty{
StringSchema: &StringSchemaProperty{
Required: jsii.Boolean(false),
// the properties below are optional
Comment: jsii.String("tenantName"),
DefaultValue: jsii.String("root"),
},
},
Name: jsii.String("tenantName"),
},
},
},
}
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.distributionConfig = distributionConfig
// Create a distribution tenant using an existing ACM certificate
cfnDistributionTenant := cloudfront.NewCfnDistributionTenant(this, jsii.String("distribution-tenant"), &CfnDistributionTenantProps{
DistributionId: myMultiTenantDistribution.DistributionId,
Domains: []*string{
jsii.String("my-tenant.my.domain.com"),
},
Name: jsii.String("my-tenant"),
Enabled: jsii.Boolean(true),
Parameters: []interface{}{
&ParameterProperty{
Name: jsii.String("tenantName"),
Value: jsii.String("app"),
},
},
Customizations: &CustomizationsProperty{
Certificate: &CertificateProperty{
Arn: jsii.String("REPLACE_WITH_ARN"),
},
},
})
Multi-tenant distribution and tenant with CloudFront-hosted certificate
A distribution tenant with CloudFront-hosted domain validation is useful if you don't currently have traffic to the domain.
Start by creating a parent multi-tenant distribution, then create the distribution tenant.
import * as route53 from 'aws-cdk-lib/aws-route53';
// Create the simple Origin
const myBucket = new s3.Bucket(this, 'myBucket');
const s3Origin = origins.S3BucketOrigin.withOriginAccessControl(myBucket, {
originAccessLevels: [cloudfront.AccessLevel.READ, cloudfront.AccessLevel.LIST],
});
// Create the Distribution construct
const myMultiTenantDistribution = new cloudfront.Distribution(this, 'cf-hosted-distribution', {
defaultBehavior: {
origin: s3Origin,
},
defaultRootObject: 'index.html', // recommended to specify
});
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
const cfnDistribution = myMultiTenantDistribution.node.defaultChild as cloudfront.CfnDistribution;
const defaultCacheBehavior: cloudfront.CfnDistribution.DefaultCacheBehaviorProperty = {
targetOriginId: myBucket.bucketArn,
viewerProtocolPolicy: 'allow-all',
compress: false,
allowedMethods: ['GET', 'HEAD'],
cachePolicyId: cloudfront.CachePolicy.CACHING_OPTIMIZED.cachePolicyId
};
// Create the updated distributionConfig
const distributionConfig: cloudfront.CfnDistribution.DistributionConfigProperty = {
defaultCacheBehavior: defaultCacheBehavior,
enabled: true,
// the properties below are optional
connectionMode: 'tenant-only',
origins: [
{
id: myBucket.bucketArn,
domainName: myBucket.bucketDomainName,
s3OriginConfig: {},
originPath: "/{{tenantName}}"
},
],
tenantConfig: {
parameterDefinitions: [
{
definition: {
stringSchema: {
required: false,
// the properties below are optional
comment: 'tenantName',
defaultValue: 'root',
},
},
name: 'tenantName',
},
],
},
};
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.distributionConfig = distributionConfig;
// Create a connection group and a cname record in an existing hosted zone to validate domain ownership
const connectionGroup = new cloudfront.CfnConnectionGroup(this, 'cf-hosted-connection-group', {
enabled: true,
ipv6Enabled: true,
name: 'my-connection-group',
});
// Import the existing hosted zone info, replacing with your hostedZoneId and zoneName
const hostedZoneId = 'YOUR_HOSTED_ZONE_ID';
const zoneName = 'my.domain.com';
const hostedZone = route53.HostedZone.fromHostedZoneAttributes(this, 'hosted-zone', {
hostedZoneId,
zoneName,
});
const record = new route53.CnameRecord(this, 'cname-record', {
domainName: connectionGroup.attrRoutingEndpoint,
zone: hostedZone,
recordName: 'cf-hosted-tenant.my.domain.com',
});
// Create the cloudfront-hosted tenant, passing in the previously created connection group
const cloudfrontHostedTenant = new cloudfront.CfnDistributionTenant(this, 'cf-hosted-tenant', {
distributionId: myMultiTenantDistribution.distributionId,
name: 'cf-hosted-tenant',
domains: ['cf-hosted-tenant.my.domain.com'],
connectionGroupId: connectionGroup.attrId,
enabled: true,
managedCertificateRequest: {
validationTokenHost: 'cloudfront'
},
});
import aws_cdk.aws_route53 as route53
# Create the simple Origin
my_bucket = s3.Bucket(self, "myBucket")
s3_origin = origins.S3BucketOrigin.with_origin_access_control(my_bucket,
origin_access_levels=[cloudfront.AccessLevel.READ, cloudfront.AccessLevel.LIST]
)
# Create the Distribution construct
my_multi_tenant_distribution = cloudfront.Distribution(self, "cf-hosted-distribution",
default_behavior=cloudfront.BehaviorOptions(
origin=s3_origin
),
default_root_object="index.html"
)
# Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
cfn_distribution = my_multi_tenant_distribution.node.default_child
default_cache_behavior = cloudfront.CfnDistribution.DefaultCacheBehaviorProperty(
target_origin_id=my_bucket.bucket_arn,
viewer_protocol_policy="allow-all",
compress=False,
allowed_methods=["GET", "HEAD"],
cache_policy_id=cloudfront.CachePolicy.CACHING_OPTIMIZED.cache_policy_id
)
# Create the updated distributionConfig
distribution_config = cloudfront.CfnDistribution.DistributionConfigProperty(
default_cache_behavior=default_cache_behavior,
enabled=True,
# the properties below are optional
connection_mode="tenant-only",
origins=[cloudfront.CfnDistribution.OriginProperty(
id=my_bucket.bucket_arn,
domain_name=my_bucket.bucket_domain_name,
s3_origin_config=cloudfront.CfnDistribution.S3OriginConfigProperty(),
origin_path="/{{tenantName}}"
)
],
tenant_config=cloudfront.CfnDistribution.TenantConfigProperty(
parameter_definitions=[cloudfront.CfnDistribution.ParameterDefinitionProperty(
definition=cloudfront.CfnDistribution.DefinitionProperty(
string_schema=cloudfront.CfnDistribution.StringSchemaProperty(
required=False,
# the properties below are optional
comment="tenantName",
default_value="root"
)
),
name="tenantName"
)
]
)
)
# Override the distribution configuration to enable multi-tenancy.
cfn_distribution.distribution_config = distribution_config
# Create a connection group and a cname record in an existing hosted zone to validate domain ownership
connection_group = cloudfront.CfnConnectionGroup(self, "cf-hosted-connection-group",
enabled=True,
ipv6_enabled=True,
name="my-connection-group"
)
# Import the existing hosted zone info, replacing with your hostedZoneId and zoneName
hosted_zone_id = "YOUR_HOSTED_ZONE_ID"
zone_name = "my.domain.com"
hosted_zone = route53.HostedZone.from_hosted_zone_attributes(self, "hosted-zone",
hosted_zone_id=hosted_zone_id,
zone_name=zone_name
)
record = route53.CnameRecord(self, "cname-record",
domain_name=connection_group.attr_routing_endpoint,
zone=hosted_zone,
record_name="cf-hosted-tenant.my.domain.com"
)
# Create the cloudfront-hosted tenant, passing in the previously created connection group
cloudfront_hosted_tenant = cloudfront.CfnDistributionTenant(self, "cf-hosted-tenant",
distribution_id=my_multi_tenant_distribution.distribution_id,
name="cf-hosted-tenant",
domains=["cf-hosted-tenant.my.domain.com"],
connection_group_id=connection_group.attr_id,
enabled=True,
managed_certificate_request=cloudfront.CfnDistributionTenant.ManagedCertificateRequestProperty(
validation_token_host="cloudfront"
)
)
import software.amazon.awscdk.services.route53.*;
// Create the simple Origin
Bucket myBucket = new Bucket(this, "myBucket");
IOrigin s3Origin = S3BucketOrigin.withOriginAccessControl(myBucket, S3BucketOriginWithOACProps.builder()
.originAccessLevels(List.of(AccessLevel.READ, AccessLevel.LIST))
.build());
// Create the Distribution construct
Distribution myMultiTenantDistribution = Distribution.Builder.create(this, "cf-hosted-distribution")
.defaultBehavior(BehaviorOptions.builder()
.origin(s3Origin)
.build())
.defaultRootObject("index.html")
.build();
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
CfnDistribution cfnDistribution = (CfnDistribution)myMultiTenantDistribution.getNode().getDefaultChild();
DefaultCacheBehaviorProperty defaultCacheBehavior = DefaultCacheBehaviorProperty.builder()
.targetOriginId(myBucket.getBucketArn())
.viewerProtocolPolicy("allow-all")
.compress(false)
.allowedMethods(List.of("GET", "HEAD"))
.cachePolicyId(CachePolicy.CACHING_OPTIMIZED.getCachePolicyId())
.build();
// Create the updated distributionConfig
DistributionConfigProperty distributionConfig = DistributionConfigProperty.builder()
.defaultCacheBehavior(defaultCacheBehavior)
.enabled(true)
// the properties below are optional
.connectionMode("tenant-only")
.origins(List.of(OriginProperty.builder()
.id(myBucket.getBucketArn())
.domainName(myBucket.getBucketDomainName())
.s3OriginConfig(S3OriginConfigProperty.builder().build())
.originPath("/{{tenantName}}")
.build()))
.tenantConfig(TenantConfigProperty.builder()
.parameterDefinitions(List.of(ParameterDefinitionProperty.builder()
.definition(DefinitionProperty.builder()
.stringSchema(StringSchemaProperty.builder()
.required(false)
// the properties below are optional
.comment("tenantName")
.defaultValue("root")
.build())
.build())
.name("tenantName")
.build()))
.build())
.build();
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.getDistributionConfig() = distributionConfig;
// Create a connection group and a cname record in an existing hosted zone to validate domain ownership
CfnConnectionGroup connectionGroup = CfnConnectionGroup.Builder.create(this, "cf-hosted-connection-group")
.enabled(true)
.ipv6Enabled(true)
.name("my-connection-group")
.build();
// Import the existing hosted zone info, replacing with your hostedZoneId and zoneName
String hostedZoneId = "YOUR_HOSTED_ZONE_ID";
String zoneName = "my.domain.com";
IHostedZone hostedZone = HostedZone.fromHostedZoneAttributes(this, "hosted-zone", HostedZoneAttributes.builder()
.hostedZoneId(hostedZoneId)
.zoneName(zoneName)
.build());
CnameRecord record = CnameRecord.Builder.create(this, "cname-record")
.domainName(connectionGroup.getAttrRoutingEndpoint())
.zone(hostedZone)
.recordName("cf-hosted-tenant.my.domain.com")
.build();
// Create the cloudfront-hosted tenant, passing in the previously created connection group
CfnDistributionTenant cloudfrontHostedTenant = CfnDistributionTenant.Builder.create(this, "cf-hosted-tenant")
.distributionId(myMultiTenantDistribution.getDistributionId())
.name("cf-hosted-tenant")
.domains(List.of("cf-hosted-tenant.my.domain.com"))
.connectionGroupId(connectionGroup.getAttrId())
.enabled(true)
.managedCertificateRequest(ManagedCertificateRequestProperty.builder()
.validationTokenHost("cloudfront")
.build())
.build();
using Amazon.CDK.AWS.Route53;
// Create the simple Origin
var myBucket = new Bucket(this, "myBucket");
var s3Origin = S3BucketOrigin.WithOriginAccessControl(myBucket, new S3BucketOriginWithOACProps {
OriginAccessLevels = new [] { AccessLevel.READ, AccessLevel.LIST }
});
// Create the Distribution construct
var myMultiTenantDistribution = new Distribution(this, "cf-hosted-distribution", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = s3Origin
},
DefaultRootObject = "index.html"
});
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
var cfnDistribution = (CfnDistribution)myMultiTenantDistribution.Node.DefaultChild;
var defaultCacheBehavior = new DefaultCacheBehaviorProperty {
TargetOriginId = myBucket.BucketArn,
ViewerProtocolPolicy = "allow-all",
Compress = false,
AllowedMethods = new [] { "GET", "HEAD" },
CachePolicyId = CachePolicy.CACHING_OPTIMIZED.CachePolicyId
};
// Create the updated distributionConfig
var distributionConfig = new DistributionConfigProperty {
DefaultCacheBehavior = defaultCacheBehavior,
Enabled = true,
// the properties below are optional
ConnectionMode = "tenant-only",
Origins = new [] { new OriginProperty {
Id = myBucket.BucketArn,
DomainName = myBucket.BucketDomainName,
S3OriginConfig = new S3OriginConfigProperty { },
OriginPath = "/{{tenantName}}"
} },
TenantConfig = new TenantConfigProperty {
ParameterDefinitions = new [] { new ParameterDefinitionProperty {
Definition = new DefinitionProperty {
StringSchema = new StringSchemaProperty {
Required = false,
// the properties below are optional
Comment = "tenantName",
DefaultValue = "root"
}
},
Name = "tenantName"
} }
}
};
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.DistributionConfig = distributionConfig;
// Create a connection group and a cname record in an existing hosted zone to validate domain ownership
var connectionGroup = new CfnConnectionGroup(this, "cf-hosted-connection-group", new CfnConnectionGroupProps {
Enabled = true,
Ipv6Enabled = true,
Name = "my-connection-group"
});
// Import the existing hosted zone info, replacing with your hostedZoneId and zoneName
var hostedZoneId = "YOUR_HOSTED_ZONE_ID";
var zoneName = "my.domain.com";
var hostedZone = HostedZone.FromHostedZoneAttributes(this, "hosted-zone", new HostedZoneAttributes {
HostedZoneId = hostedZoneId,
ZoneName = zoneName
});
var record = new CnameRecord(this, "cname-record", new CnameRecordProps {
DomainName = connectionGroup.AttrRoutingEndpoint,
Zone = hostedZone,
RecordName = "cf-hosted-tenant.my.domain.com"
});
// Create the cloudfront-hosted tenant, passing in the previously created connection group
var cloudfrontHostedTenant = new CfnDistributionTenant(this, "cf-hosted-tenant", new CfnDistributionTenantProps {
DistributionId = myMultiTenantDistribution.DistributionId,
Name = "cf-hosted-tenant",
Domains = new [] { "cf-hosted-tenant.my.domain.com" },
ConnectionGroupId = connectionGroup.AttrId,
Enabled = true,
ManagedCertificateRequest = new ManagedCertificateRequestProperty {
ValidationTokenHost = "cloudfront"
}
});
import "github.com/aws/aws-cdk-go/awscdk"
// Create the simple Origin
myBucket := s3.NewBucket(this, jsii.String("myBucket"))
s3Origin := origins.S3BucketOrigin_WithOriginAccessControl(myBucket, &S3BucketOriginWithOACProps{
OriginAccessLevels: []AccessLevel{
cloudfront.AccessLevel_READ,
cloudfront.AccessLevel_LIST,
},
})
// Create the Distribution construct
myMultiTenantDistribution := cloudfront.NewDistribution(this, jsii.String("cf-hosted-distribution"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: s3Origin,
},
DefaultRootObject: jsii.String("index.html"),
})
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
cfnDistribution := myMultiTenantDistribution.Node.defaultChild.(CfnDistribution)
defaultCacheBehavior := &DefaultCacheBehaviorProperty{
TargetOriginId: myBucket.bucketArn,
ViewerProtocolPolicy: jsii.String("allow-all"),
Compress: jsii.Boolean(false),
AllowedMethods: []*string{
jsii.String("GET"),
jsii.String("HEAD"),
},
CachePolicyId: cloudfront.CachePolicy_CACHING_OPTIMIZED().CachePolicyId,
}
// Create the updated distributionConfig
distributionConfig := &DistributionConfigProperty{
DefaultCacheBehavior: defaultCacheBehavior,
Enabled: jsii.Boolean(true),
// the properties below are optional
ConnectionMode: jsii.String("tenant-only"),
Origins: []interface{}{
&OriginProperty{
Id: myBucket.bucketArn,
DomainName: myBucket.BucketDomainName,
S3OriginConfig: &S3OriginConfigProperty{
},
OriginPath: jsii.String("/{{tenantName}}"),
},
},
TenantConfig: &TenantConfigProperty{
ParameterDefinitions: []interface{}{
&ParameterDefinitionProperty{
Definition: &DefinitionProperty{
StringSchema: &StringSchemaProperty{
Required: jsii.Boolean(false),
// the properties below are optional
Comment: jsii.String("tenantName"),
DefaultValue: jsii.String("root"),
},
},
Name: jsii.String("tenantName"),
},
},
},
}
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.distributionConfig = distributionConfig
// Create a connection group and a cname record in an existing hosted zone to validate domain ownership
connectionGroup := cloudfront.NewCfnConnectionGroup(this, jsii.String("cf-hosted-connection-group"), &CfnConnectionGroupProps{
Enabled: jsii.Boolean(true),
Ipv6Enabled: jsii.Boolean(true),
Name: jsii.String("my-connection-group"),
})
// Import the existing hosted zone info, replacing with your hostedZoneId and zoneName
hostedZoneId := "YOUR_HOSTED_ZONE_ID"
zoneName := "my.domain.com"
hostedZone := route53.HostedZone_FromHostedZoneAttributes(this, jsii.String("hosted-zone"), &HostedZoneAttributes{
HostedZoneId: jsii.String(HostedZoneId),
ZoneName: jsii.String(ZoneName),
})
record := route53.NewCnameRecord(this, jsii.String("cname-record"), &CnameRecordProps{
DomainName: connectionGroup.attrRoutingEndpoint,
Zone: hostedZone,
RecordName: jsii.String("cf-hosted-tenant.my.domain.com"),
})
// Create the cloudfront-hosted tenant, passing in the previously created connection group
cloudfrontHostedTenant := cloudfront.NewCfnDistributionTenant(this, jsii.String("cf-hosted-tenant"), &CfnDistributionTenantProps{
DistributionId: myMultiTenantDistribution.DistributionId,
Name: jsii.String("cf-hosted-tenant"),
Domains: []*string{
jsii.String("cf-hosted-tenant.my.domain.com"),
},
ConnectionGroupId: connectionGroup.attrId,
Enabled: jsii.Boolean(true),
ManagedCertificateRequest: &ManagedCertificateRequestProperty{
ValidationTokenHost: jsii.String("cloudfront"),
},
})
Multi-tenant distribution and tenant with self-hosted certificate
A tenant with self-hosted domain validation is useful if you already have traffic to the domain and can't tolerate downtime during migration to multi-tenant architecture.
The tenant will be created, and the managed certificate will be awaiting validation of domain ownership. You can then validate domain ownership via http redirect or token file upload. More details here
Traffic won't be migrated until you update your hosted zone to point the tenant domain to the CloudFront RoutingEndpoint.
Start by creating a parent multi-tenant distribution
// Create the simple Origin
const myBucket = new s3.Bucket(this, 'myBucket');
const s3Origin = origins.S3BucketOrigin.withOriginAccessControl(myBucket, {
originAccessLevels: [cloudfront.AccessLevel.READ, cloudfront.AccessLevel.LIST],
});
// Create the Distribution construct
const myMultiTenantDistribution = new cloudfront.Distribution(this, 'cf-hosted-distribution', {
defaultBehavior: {
origin: s3Origin,
},
defaultRootObject: 'index.html', // recommended to specify
});
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
const cfnDistribution = myMultiTenantDistribution.node.defaultChild as cloudfront.CfnDistribution;
const defaultCacheBehavior: cloudfront.CfnDistribution.DefaultCacheBehaviorProperty = {
targetOriginId: myBucket.bucketArn,
viewerProtocolPolicy: 'allow-all',
compress: false,
allowedMethods: ['GET', 'HEAD'],
cachePolicyId: cloudfront.CachePolicy.CACHING_OPTIMIZED.cachePolicyId
};
// Create the updated distributionConfig
const distributionConfig: cloudfront.CfnDistribution.DistributionConfigProperty = {
defaultCacheBehavior: defaultCacheBehavior,
enabled: true,
// the properties below are optional
connectionMode: 'tenant-only',
origins: [
{
id: myBucket.bucketArn,
domainName: myBucket.bucketDomainName,
s3OriginConfig: {},
originPath: "/{{tenantName}}"
},
],
tenantConfig: {
parameterDefinitions: [
{
definition: {
stringSchema: {
required: false,
// the properties below are optional
comment: 'tenantName',
defaultValue: 'root',
},
},
name: 'tenantName',
},
],
},
};
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.distributionConfig = distributionConfig;
// Create a connection group so we have access to the RoutingEndpoint associated with the tenant we are about to create
const connectionGroup = new cloudfront.CfnConnectionGroup(this, 'self-hosted-connection-group', {
enabled: true,
ipv6Enabled: true,
name: 'self-hosted-connection-group',
});
// Export the RoutingEndpoint, skip this step if you'd prefer to fetch it from the CloudFront console or via Cloudfront.ListConnectionGroups API
new CfnOutput(this, 'RoutingEndpoint', {
value: connectionGroup.attrRoutingEndpoint,
description: 'CloudFront Routing Endpoint to be added to my hosted zone CNAME records',
});
// Create a distribution tenant with a self-hosted domain.
const selfHostedTenant = new cloudfront.CfnDistributionTenant(this, 'self-hosted-tenant', {
distributionId: myMultiTenantDistribution.distributionId,
connectionGroupId: connectionGroup.attrId,
name: 'self-hosted-tenant',
domains: ['self-hosted-tenant.my.domain.com'],
enabled: true,
managedCertificateRequest: {
primaryDomainName: 'self-hosted-tenant.my.domain.com',
validationTokenHost: 'self-hosted',
},
});
# Create the simple Origin
my_bucket = s3.Bucket(self, "myBucket")
s3_origin = origins.S3BucketOrigin.with_origin_access_control(my_bucket,
origin_access_levels=[cloudfront.AccessLevel.READ, cloudfront.AccessLevel.LIST]
)
# Create the Distribution construct
my_multi_tenant_distribution = cloudfront.Distribution(self, "cf-hosted-distribution",
default_behavior=cloudfront.BehaviorOptions(
origin=s3_origin
),
default_root_object="index.html"
)
# Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
cfn_distribution = my_multi_tenant_distribution.node.default_child
default_cache_behavior = cloudfront.CfnDistribution.DefaultCacheBehaviorProperty(
target_origin_id=my_bucket.bucket_arn,
viewer_protocol_policy="allow-all",
compress=False,
allowed_methods=["GET", "HEAD"],
cache_policy_id=cloudfront.CachePolicy.CACHING_OPTIMIZED.cache_policy_id
)
# Create the updated distributionConfig
distribution_config = cloudfront.CfnDistribution.DistributionConfigProperty(
default_cache_behavior=default_cache_behavior,
enabled=True,
# the properties below are optional
connection_mode="tenant-only",
origins=[cloudfront.CfnDistribution.OriginProperty(
id=my_bucket.bucket_arn,
domain_name=my_bucket.bucket_domain_name,
s3_origin_config=cloudfront.CfnDistribution.S3OriginConfigProperty(),
origin_path="/{{tenantName}}"
)
],
tenant_config=cloudfront.CfnDistribution.TenantConfigProperty(
parameter_definitions=[cloudfront.CfnDistribution.ParameterDefinitionProperty(
definition=cloudfront.CfnDistribution.DefinitionProperty(
string_schema=cloudfront.CfnDistribution.StringSchemaProperty(
required=False,
# the properties below are optional
comment="tenantName",
default_value="root"
)
),
name="tenantName"
)
]
)
)
# Override the distribution configuration to enable multi-tenancy.
cfn_distribution.distribution_config = distribution_config
# Create a connection group so we have access to the RoutingEndpoint associated with the tenant we are about to create
connection_group = cloudfront.CfnConnectionGroup(self, "self-hosted-connection-group",
enabled=True,
ipv6_enabled=True,
name="self-hosted-connection-group"
)
# Export the RoutingEndpoint, skip this step if you'd prefer to fetch it from the CloudFront console or via Cloudfront.ListConnectionGroups API
CfnOutput(self, "RoutingEndpoint",
value=connection_group.attr_routing_endpoint,
description="CloudFront Routing Endpoint to be added to my hosted zone CNAME records"
)
# Create a distribution tenant with a self-hosted domain.
self_hosted_tenant = cloudfront.CfnDistributionTenant(self, "self-hosted-tenant",
distribution_id=my_multi_tenant_distribution.distribution_id,
connection_group_id=connection_group.attr_id,
name="self-hosted-tenant",
domains=["self-hosted-tenant.my.domain.com"],
enabled=True,
managed_certificate_request=cloudfront.CfnDistributionTenant.ManagedCertificateRequestProperty(
primary_domain_name="self-hosted-tenant.my.domain.com",
validation_token_host="self-hosted"
)
)
// Create the simple Origin
Bucket myBucket = new Bucket(this, "myBucket");
IOrigin s3Origin = S3BucketOrigin.withOriginAccessControl(myBucket, S3BucketOriginWithOACProps.builder()
.originAccessLevels(List.of(AccessLevel.READ, AccessLevel.LIST))
.build());
// Create the Distribution construct
Distribution myMultiTenantDistribution = Distribution.Builder.create(this, "cf-hosted-distribution")
.defaultBehavior(BehaviorOptions.builder()
.origin(s3Origin)
.build())
.defaultRootObject("index.html")
.build();
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
CfnDistribution cfnDistribution = (CfnDistribution)myMultiTenantDistribution.getNode().getDefaultChild();
DefaultCacheBehaviorProperty defaultCacheBehavior = DefaultCacheBehaviorProperty.builder()
.targetOriginId(myBucket.getBucketArn())
.viewerProtocolPolicy("allow-all")
.compress(false)
.allowedMethods(List.of("GET", "HEAD"))
.cachePolicyId(CachePolicy.CACHING_OPTIMIZED.getCachePolicyId())
.build();
// Create the updated distributionConfig
DistributionConfigProperty distributionConfig = DistributionConfigProperty.builder()
.defaultCacheBehavior(defaultCacheBehavior)
.enabled(true)
// the properties below are optional
.connectionMode("tenant-only")
.origins(List.of(OriginProperty.builder()
.id(myBucket.getBucketArn())
.domainName(myBucket.getBucketDomainName())
.s3OriginConfig(S3OriginConfigProperty.builder().build())
.originPath("/{{tenantName}}")
.build()))
.tenantConfig(TenantConfigProperty.builder()
.parameterDefinitions(List.of(ParameterDefinitionProperty.builder()
.definition(DefinitionProperty.builder()
.stringSchema(StringSchemaProperty.builder()
.required(false)
// the properties below are optional
.comment("tenantName")
.defaultValue("root")
.build())
.build())
.name("tenantName")
.build()))
.build())
.build();
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.getDistributionConfig() = distributionConfig;
// Create a connection group so we have access to the RoutingEndpoint associated with the tenant we are about to create
CfnConnectionGroup connectionGroup = CfnConnectionGroup.Builder.create(this, "self-hosted-connection-group")
.enabled(true)
.ipv6Enabled(true)
.name("self-hosted-connection-group")
.build();
// Export the RoutingEndpoint, skip this step if you'd prefer to fetch it from the CloudFront console or via Cloudfront.ListConnectionGroups API
// Export the RoutingEndpoint, skip this step if you'd prefer to fetch it from the CloudFront console or via Cloudfront.ListConnectionGroups API
CfnOutput.Builder.create(this, "RoutingEndpoint")
.value(connectionGroup.getAttrRoutingEndpoint())
.description("CloudFront Routing Endpoint to be added to my hosted zone CNAME records")
.build();
// Create a distribution tenant with a self-hosted domain.
CfnDistributionTenant selfHostedTenant = CfnDistributionTenant.Builder.create(this, "self-hosted-tenant")
.distributionId(myMultiTenantDistribution.getDistributionId())
.connectionGroupId(connectionGroup.getAttrId())
.name("self-hosted-tenant")
.domains(List.of("self-hosted-tenant.my.domain.com"))
.enabled(true)
.managedCertificateRequest(ManagedCertificateRequestProperty.builder()
.primaryDomainName("self-hosted-tenant.my.domain.com")
.validationTokenHost("self-hosted")
.build())
.build();
// Create the simple Origin
var myBucket = new Bucket(this, "myBucket");
var s3Origin = S3BucketOrigin.WithOriginAccessControl(myBucket, new S3BucketOriginWithOACProps {
OriginAccessLevels = new [] { AccessLevel.READ, AccessLevel.LIST }
});
// Create the Distribution construct
var myMultiTenantDistribution = new Distribution(this, "cf-hosted-distribution", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = s3Origin
},
DefaultRootObject = "index.html"
});
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
var cfnDistribution = (CfnDistribution)myMultiTenantDistribution.Node.DefaultChild;
var defaultCacheBehavior = new DefaultCacheBehaviorProperty {
TargetOriginId = myBucket.BucketArn,
ViewerProtocolPolicy = "allow-all",
Compress = false,
AllowedMethods = new [] { "GET", "HEAD" },
CachePolicyId = CachePolicy.CACHING_OPTIMIZED.CachePolicyId
};
// Create the updated distributionConfig
var distributionConfig = new DistributionConfigProperty {
DefaultCacheBehavior = defaultCacheBehavior,
Enabled = true,
// the properties below are optional
ConnectionMode = "tenant-only",
Origins = new [] { new OriginProperty {
Id = myBucket.BucketArn,
DomainName = myBucket.BucketDomainName,
S3OriginConfig = new S3OriginConfigProperty { },
OriginPath = "/{{tenantName}}"
} },
TenantConfig = new TenantConfigProperty {
ParameterDefinitions = new [] { new ParameterDefinitionProperty {
Definition = new DefinitionProperty {
StringSchema = new StringSchemaProperty {
Required = false,
// the properties below are optional
Comment = "tenantName",
DefaultValue = "root"
}
},
Name = "tenantName"
} }
}
};
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.DistributionConfig = distributionConfig;
// Create a connection group so we have access to the RoutingEndpoint associated with the tenant we are about to create
var connectionGroup = new CfnConnectionGroup(this, "self-hosted-connection-group", new CfnConnectionGroupProps {
Enabled = true,
Ipv6Enabled = true,
Name = "self-hosted-connection-group"
});
// Export the RoutingEndpoint, skip this step if you'd prefer to fetch it from the CloudFront console or via Cloudfront.ListConnectionGroups API
// Export the RoutingEndpoint, skip this step if you'd prefer to fetch it from the CloudFront console or via Cloudfront.ListConnectionGroups API
new CfnOutput(this, "RoutingEndpoint", new CfnOutputProps {
Value = connectionGroup.AttrRoutingEndpoint,
Description = "CloudFront Routing Endpoint to be added to my hosted zone CNAME records"
});
// Create a distribution tenant with a self-hosted domain.
var selfHostedTenant = new CfnDistributionTenant(this, "self-hosted-tenant", new CfnDistributionTenantProps {
DistributionId = myMultiTenantDistribution.DistributionId,
ConnectionGroupId = connectionGroup.AttrId,
Name = "self-hosted-tenant",
Domains = new [] { "self-hosted-tenant.my.domain.com" },
Enabled = true,
ManagedCertificateRequest = new ManagedCertificateRequestProperty {
PrimaryDomainName = "self-hosted-tenant.my.domain.com",
ValidationTokenHost = "self-hosted"
}
});
// Create the simple Origin
myBucket := s3.NewBucket(this, jsii.String("myBucket"))
s3Origin := origins.S3BucketOrigin_WithOriginAccessControl(myBucket, &S3BucketOriginWithOACProps{
OriginAccessLevels: []AccessLevel{
cloudfront.AccessLevel_READ,
cloudfront.AccessLevel_LIST,
},
})
// Create the Distribution construct
myMultiTenantDistribution := cloudfront.NewDistribution(this, jsii.String("cf-hosted-distribution"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: s3Origin,
},
DefaultRootObject: jsii.String("index.html"),
})
// Access the underlying L1 CfnDistribution to configure SaaS Manager properties which are not yet available in the L2 Distribution construct
cfnDistribution := myMultiTenantDistribution.Node.defaultChild.(CfnDistribution)
defaultCacheBehavior := &DefaultCacheBehaviorProperty{
TargetOriginId: myBucket.bucketArn,
ViewerProtocolPolicy: jsii.String("allow-all"),
Compress: jsii.Boolean(false),
AllowedMethods: []*string{
jsii.String("GET"),
jsii.String("HEAD"),
},
CachePolicyId: cloudfront.CachePolicy_CACHING_OPTIMIZED().CachePolicyId,
}
// Create the updated distributionConfig
distributionConfig := &DistributionConfigProperty{
DefaultCacheBehavior: defaultCacheBehavior,
Enabled: jsii.Boolean(true),
// the properties below are optional
ConnectionMode: jsii.String("tenant-only"),
Origins: []interface{}{
&OriginProperty{
Id: myBucket.bucketArn,
DomainName: myBucket.BucketDomainName,
S3OriginConfig: &S3OriginConfigProperty{
},
OriginPath: jsii.String("/{{tenantName}}"),
},
},
TenantConfig: &TenantConfigProperty{
ParameterDefinitions: []interface{}{
&ParameterDefinitionProperty{
Definition: &DefinitionProperty{
StringSchema: &StringSchemaProperty{
Required: jsii.Boolean(false),
// the properties below are optional
Comment: jsii.String("tenantName"),
DefaultValue: jsii.String("root"),
},
},
Name: jsii.String("tenantName"),
},
},
},
}
// Override the distribution configuration to enable multi-tenancy.
cfnDistribution.distributionConfig = distributionConfig
// Create a connection group so we have access to the RoutingEndpoint associated with the tenant we are about to create
connectionGroup := cloudfront.NewCfnConnectionGroup(this, jsii.String("self-hosted-connection-group"), &CfnConnectionGroupProps{
Enabled: jsii.Boolean(true),
Ipv6Enabled: jsii.Boolean(true),
Name: jsii.String("self-hosted-connection-group"),
})
// Export the RoutingEndpoint, skip this step if you'd prefer to fetch it from the CloudFront console or via Cloudfront.ListConnectionGroups API
// Export the RoutingEndpoint, skip this step if you'd prefer to fetch it from the CloudFront console or via Cloudfront.ListConnectionGroups API
awscdk.NewCfnOutput(this, jsii.String("RoutingEndpoint"), &CfnOutputProps{
Value: connectionGroup.attrRoutingEndpoint,
Description: jsii.String("CloudFront Routing Endpoint to be added to my hosted zone CNAME records"),
})
// Create a distribution tenant with a self-hosted domain.
selfHostedTenant := cloudfront.NewCfnDistributionTenant(this, jsii.String("self-hosted-tenant"), &CfnDistributionTenantProps{
DistributionId: myMultiTenantDistribution.DistributionId,
ConnectionGroupId: connectionGroup.attrId,
Name: jsii.String("self-hosted-tenant"),
Domains: []*string{
jsii.String("self-hosted-tenant.my.domain.com"),
},
Enabled: jsii.Boolean(true),
ManagedCertificateRequest: &ManagedCertificateRequestProperty{
PrimaryDomainName: jsii.String("self-hosted-tenant.my.domain.com"),
ValidationTokenHost: jsii.String("self-hosted"),
},
})
While CDK is deploying, it will attempt to validate domain ownership by confirming that a validation token is served directly from your domain, or via http redirect.
follow the steps here to complete domain setup before deploying this CDK stack, or while CDK is in the waiting state during tenant creation. Refer to the section "I have existing traffic"
A simple option for validating via http redirect, would be to add a rewrite rule like so to your server (Apache in this example)
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/\.well-known/pki-validation/(.+)$ [NC]
RewriteRule ^(.*)$ https://validation.us-east-1.acm-validations.aws/%{ENV:AWS_ACCOUNT_ID}/.well-known/pki-validation/%1 [R=301,L]
Then, when you are ready to accept traffic, follow the steps here using the RoutingEndpoint from above to configure DNS to point to CloudFront.
VPC origins
You can use CloudFront to deliver content from applications that are hosted in your virtual private cloud (VPC) private subnets. You can use Application Load Balancers (ALBs), Network Load Balancers (NLBs), and EC2 instances in private subnets as VPC origins.
Learn more about Restrict access with VPC origins.
See the README of the aws-cdk-lib/aws-cloudfront-origins module for more information on setting up VPC origins.
Domain Names and Certificates
When you create a distribution, CloudFront assigns a domain name for the distribution, for example: d111111abcdef8.cloudfront.net; this value can be retrieved from distribution.distributionDomainName. CloudFront distributions use a default certificate (*.cloudfront.net) to support HTTPS by default. If you want to use your own domain name, such as www.example.com, you must associate a certificate with your distribution that contains your domain name, and provide one (or more) domain names from the certificate for the distribution.
The certificate must be present in the AWS Certificate Manager (ACM) service in the US East (N. Virginia) region; the certificate may either be created by ACM, or created elsewhere and imported into ACM. When a certificate is used, the distribution will support HTTPS connections from SNI only and a minimum protocol version of TLSv1.2_2021 if the @aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021 feature flag is set, and TLSv1.2_2019 otherwise.
// To use your own domain name in a Distribution, you must associate a certificate
import * as acm from 'aws-cdk-lib/aws-certificatemanager';
import * as route53 from 'aws-cdk-lib/aws-route53';
declare const hostedZone: route53.HostedZone;
const myCertificate = new acm.Certificate(this, 'mySiteCert', {
domainName: 'www.example.com',
validation: acm.CertificateValidation.fromDns(hostedZone),
});
declare const myBucket: s3.Bucket;
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.S3Origin(myBucket) },
domainNames: ['www.example.com'],
certificate: myCertificate,
});
# To use your own domain name in a Distribution, you must associate a certificate
import aws_cdk.aws_certificatemanager as acm
import aws_cdk.aws_route53 as route53
# hosted_zone: route53.HostedZone
# my_bucket: s3.Bucket
my_certificate = acm.Certificate(self, "mySiteCert",
domain_name="www.example.com",
validation=acm.CertificateValidation.from_dns(hosted_zone)
)
cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(origin=origins.S3Origin(my_bucket)),
domain_names=["www.example.com"],
certificate=my_certificate
)
// To use your own domain name in a Distribution, you must associate a certificate
import software.amazon.awscdk.services.certificatemanager.*;
import software.amazon.awscdk.services.route53.*;
HostedZone hostedZone;
Bucket myBucket;
Certificate myCertificate = Certificate.Builder.create(this, "mySiteCert")
.domainName("www.example.com")
.validation(CertificateValidation.fromDns(hostedZone))
.build();
Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder().origin(new S3Origin(myBucket)).build())
.domainNames(List.of("www.example.com"))
.certificate(myCertificate)
.build();
// To use your own domain name in a Distribution, you must associate a certificate
using Amazon.CDK.AWS.CertificateManager;
using Amazon.CDK.AWS.Route53;
HostedZone hostedZone;
Bucket myBucket;
var myCertificate = new Certificate(this, "mySiteCert", new CertificateProps {
DomainName = "www.example.com",
Validation = CertificateValidation.FromDns(hostedZone)
});
new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions { Origin = new S3Origin(myBucket) },
DomainNames = new [] { "www.example.com" },
Certificate = myCertificate
});
// To use your own domain name in a Distribution, you must associate a certificate
import "github.com/aws/aws-cdk-go/awscdk"
import route53 "github.com/aws/aws-cdk-go/awscdk"
var hostedZone HostedZone
var myBucket Bucket
myCertificate := acm.NewCertificate(this, jsii.String("mySiteCert"), &CertificateProps{
DomainName: jsii.String("www.example.com"),
Validation: acm.CertificateValidation_FromDns(hostedZone),
})
cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewS3Origin(myBucket),
},
DomainNames: []*string{
jsii.String("www.example.com"),
},
Certificate: myCertificate,
})
However, you can customize the minimum protocol version for the certificate while creating the distribution using minimumProtocolVersion property.
// Create a Distribution with a custom domain name and a minimum protocol version.
declare const myBucket: s3.Bucket;
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.S3Origin(myBucket) },
domainNames: ['www.example.com'],
minimumProtocolVersion: cloudfront.SecurityPolicyProtocol.TLS_V1_2016,
sslSupportMethod: cloudfront.SSLMethod.SNI,
});
# Create a Distribution with a custom domain name and a minimum protocol version.
# my_bucket: s3.Bucket
cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(origin=origins.S3Origin(my_bucket)),
domain_names=["www.example.com"],
minimum_protocol_version=cloudfront.SecurityPolicyProtocol.TLS_V1_2016,
ssl_support_method=cloudfront.SSLMethod.SNI
)
// Create a Distribution with a custom domain name and a minimum protocol version.
Bucket myBucket;
Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder().origin(new S3Origin(myBucket)).build())
.domainNames(List.of("www.example.com"))
.minimumProtocolVersion(SecurityPolicyProtocol.TLS_V1_2016)
.sslSupportMethod(SSLMethod.SNI)
.build();
// Create a Distribution with a custom domain name and a minimum protocol version.
Bucket myBucket;
new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions { Origin = new S3Origin(myBucket) },
DomainNames = new [] { "www.example.com" },
MinimumProtocolVersion = SecurityPolicyProtocol.TLS_V1_2016,
SslSupportMethod = SSLMethod.SNI
});
// Create a Distribution with a custom domain name and a minimum protocol version.
var myBucket Bucket
cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewS3Origin(myBucket),
},
DomainNames: []*string{
jsii.String("www.example.com"),
},
MinimumProtocolVersion: cloudfront.SecurityPolicyProtocol_TLS_V1_2016,
SslSupportMethod: cloudfront.SSLMethod_SNI,
})
Moving an alternate domain name to a different distribution
When you try to add an alternate domain name to a distribution but the alternate domain name is already in use on a different distribution, you get a CNAMEAlreadyExists error (One or more of the CNAMEs you provided are already associated with a different resource).
In that case, you might want to move the existing alternate domain name from one distribution (the source distribution) to another (the target distribution). The following steps are an overview of the process. For more information, see Moving an alternate domain name to a different distribution.
- Deploy the stack with the target distribution. The
certificateproperty must be specified but thedomainNamesshould be absent. - Move the alternate domain name by running CloudFront
associate-aliascommand. For the example and preconditions, see the AWS documentation above. - Specify the
domainNamesproperty with the alternative domain name, then deploy the stack again to resolve the drift at the alternative domain name.
Cross Region Certificates
This feature is currently experimental
You can enable the Stack property crossRegionReferences in order to access resources in a different stack and region. With this feature flag enabled it is possible to do something like creating a CloudFront distribution in us-east-2 and an ACM certificate in us-east-1.
import * as acm from 'aws-cdk-lib/aws-certificatemanager';
import * as route53 from 'aws-cdk-lib/aws-route53';
declare const app: App;
const stack1 = new Stack(app, 'Stack1', {
env: {
region: 'us-east-1',
},
crossRegionReferences: true,
});
const cert = new acm.Certificate(stack1, 'Cert', {
domainName: '*.example.com',
validation: acm.CertificateValidation.fromDns(route53.PublicHostedZone.fromHostedZoneId(stack1, 'Zone', 'Z0329774B51CGXTDQV3X')),
});
const stack2 = new Stack(app, 'Stack2', {
env: {
region: 'us-east-2',
},
crossRegionReferences: true,
});
new cloudfront.Distribution(stack2, 'Distribution', {
defaultBehavior: {
origin: new origins.HttpOrigin('example.com'),
},
domainNames: ['dev.example.com'],
certificate: cert,
});
from aws_cdk import Environment, Environment
import aws_cdk.aws_certificatemanager as acm
import aws_cdk.aws_route53 as route53
# app: App
stack1 = Stack(app, "Stack1",
env=Environment(
region="us-east-1"
),
cross_region_references=True
)
cert = acm.Certificate(stack1, "Cert",
domain_name="*.example.com",
validation=acm.CertificateValidation.from_dns(route53.PublicHostedZone.from_hosted_zone_id(stack1, "Zone", "Z0329774B51CGXTDQV3X"))
)
stack2 = Stack(app, "Stack2",
env=Environment(
region="us-east-2"
),
cross_region_references=True
)
cloudfront.Distribution(stack2, "Distribution",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.HttpOrigin("example.com")
),
domain_names=["dev.example.com"],
certificate=cert
)
import software.amazon.awscdk.services.certificatemanager.*;
import software.amazon.awscdk.services.route53.*;
App app;
Stack stack1 = Stack.Builder.create(app, "Stack1")
.env(Environment.builder()
.region("us-east-1")
.build())
.crossRegionReferences(true)
.build();
Certificate cert = Certificate.Builder.create(stack1, "Cert")
.domainName("*.example.com")
.validation(CertificateValidation.fromDns(PublicHostedZone.fromHostedZoneId(stack1, "Zone", "Z0329774B51CGXTDQV3X")))
.build();
Stack stack2 = Stack.Builder.create(app, "Stack2")
.env(Environment.builder()
.region("us-east-2")
.build())
.crossRegionReferences(true)
.build();
Distribution.Builder.create(stack2, "Distribution")
.defaultBehavior(BehaviorOptions.builder()
.origin(new HttpOrigin("example.com"))
.build())
.domainNames(List.of("dev.example.com"))
.certificate(cert)
.build();
using Amazon.CDK.AWS.CertificateManager;
using Amazon.CDK.AWS.Route53;
App app;
var stack1 = new Stack(app, "Stack1", new StackProps {
Env = new Environment {
Region = "us-east-1"
},
CrossRegionReferences = true
});
var cert = new Certificate(stack1, "Cert", new CertificateProps {
DomainName = "*.example.com",
Validation = CertificateValidation.FromDns(PublicHostedZone.FromHostedZoneId(stack1, "Zone", "Z0329774B51CGXTDQV3X"))
});
var stack2 = new Stack(app, "Stack2", new StackProps {
Env = new Environment {
Region = "us-east-2"
},
CrossRegionReferences = true
});
new Distribution(stack2, "Distribution", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = new HttpOrigin("example.com")
},
DomainNames = new [] { "dev.example.com" },
Certificate = cert
});
import "github.com/aws/aws-cdk-go/awscdk"
import route53 "github.com/aws/aws-cdk-go/awscdk"
var app App
stack1 := awscdk.Newstack(app, jsii.String("Stack1"), &StackProps{
Env: &Environment{
Region: jsii.String("us-east-1"),
},
CrossRegionReferences: jsii.Boolean(true),
})
cert := acm.NewCertificate(stack1, jsii.String("Cert"), &CertificateProps{
DomainName: jsii.String("*.example.com"),
Validation: acm.CertificateValidation_FromDns(route53.PublicHostedZone_FromHostedZoneId(stack1, jsii.String("Zone"), jsii.String("Z0329774B51CGXTDQV3X"))),
})
stack2 := awscdk.Newstack(app, jsii.String("Stack2"), &StackProps{
Env: &Environment{
Region: jsii.String("us-east-2"),
},
CrossRegionReferences: jsii.Boolean(true),
})
cloudfront.NewDistribution(stack2, jsii.String("Distribution"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewHttpOrigin(jsii.String("example.com")),
},
DomainNames: []*string{
jsii.String("dev.example.com"),
},
Certificate: cert,
})
Multiple Behaviors & Origins
Each distribution has a default behavior which applies to all requests to that distribution; additional behaviors may be specified for a given URL path pattern. Behaviors allow routing with multiple origins, controlling which HTTP methods to support, whether to require users to use HTTPS, and what query strings or cookies to forward to your origin, among others.
The properties of the default behavior can be adjusted as part of the distribution creation. The following example shows configuring the HTTP methods and viewer protocol policy of the cache.
// Create a Distribution with configured HTTP methods and viewer protocol policy of the cache.
declare const myBucket: s3.Bucket;
const myWebDistribution = new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: {
origin: new origins.S3Origin(myBucket),
allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
},
});
# Create a Distribution with configured HTTP methods and viewer protocol policy of the cache.
# my_bucket: s3.Bucket
my_web_distribution = cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.S3Origin(my_bucket),
allowed_methods=cloudfront.AllowedMethods.ALLOW_ALL,
viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS
)
)
// Create a Distribution with configured HTTP methods and viewer protocol policy of the cache.
Bucket myBucket;
Distribution myWebDistribution = Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder()
.origin(new S3Origin(myBucket))
.allowedMethods(AllowedMethods.ALLOW_ALL)
.viewerProtocolPolicy(ViewerProtocolPolicy.REDIRECT_TO_HTTPS)
.build())
.build();
// Create a Distribution with configured HTTP methods and viewer protocol policy of the cache.
Bucket myBucket;
var myWebDistribution = new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = new S3Origin(myBucket),
AllowedMethods = AllowedMethods.ALLOW_ALL,
ViewerProtocolPolicy = ViewerProtocolPolicy.REDIRECT_TO_HTTPS
}
});
// Create a Distribution with configured HTTP methods and viewer protocol policy of the cache.
var myBucket Bucket
myWebDistribution := cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewS3Origin(myBucket),
AllowedMethods: cloudfront.AllowedMethods_ALLOW_ALL(),
ViewerProtocolPolicy: cloudfront.ViewerProtocolPolicy_REDIRECT_TO_HTTPS,
},
})
Additional behaviors can be specified at creation, or added after the initial creation. Each additional behavior is associated with an origin, and enable customization for a specific set of resources based on a URL path pattern. For example, we can add a behavior to myWebDistribution to override the default viewer protocol policy for all of the images.
// Add a behavior to a Distribution after initial creation.
declare const myBucket: s3.Bucket;
declare const myWebDistribution: cloudfront.Distribution;
myWebDistribution.addBehavior('/images/*.jpg', new origins.S3Origin(myBucket), {
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
});
# Add a behavior to a Distribution after initial creation.
# my_bucket: s3.Bucket
# my_web_distribution: cloudfront.Distribution
my_web_distribution.add_behavior("/images/*.jpg", origins.S3Origin(my_bucket),
viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS
)
// Add a behavior to a Distribution after initial creation.
Bucket myBucket;
Distribution myWebDistribution;
myWebDistribution.addBehavior("/images/*.jpg", new S3Origin(myBucket), AddBehaviorOptions.builder()
.viewerProtocolPolicy(ViewerProtocolPolicy.REDIRECT_TO_HTTPS)
.build());
// Add a behavior to a Distribution after initial creation.
Bucket myBucket;
Distribution myWebDistribution;
myWebDistribution.AddBehavior("/images/*.jpg", new S3Origin(myBucket), new AddBehaviorOptions {
ViewerProtocolPolicy = ViewerProtocolPolicy.REDIRECT_TO_HTTPS
});
// Add a behavior to a Distribution after initial creation.
var myBucket Bucket
var myWebDistribution Distribution
myWebDistribution.AddBehavior(jsii.String("/images/*.jpg"), origins.NewS3Origin(myBucket), &AddBehaviorOptions{
ViewerProtocolPolicy: cloudfront.ViewerProtocolPolicy_REDIRECT_TO_HTTPS,
})
These behaviors can also be specified at distribution creation time.
// Create a Distribution with additional behaviors at creation time.
declare const myBucket: s3.Bucket;
const bucketOrigin = new origins.S3Origin(myBucket);
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: {
origin: bucketOrigin,
allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
},
additionalBehaviors: {
'/images/*.jpg': {
origin: bucketOrigin,
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
},
},
});
# Create a Distribution with additional behaviors at creation time.
# my_bucket: s3.Bucket
bucket_origin = origins.S3Origin(my_bucket)
cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(
origin=bucket_origin,
allowed_methods=cloudfront.AllowedMethods.ALLOW_ALL,
viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS
),
additional_behaviors={
"/images/*.jpg": cloudfront.BehaviorOptions(
origin=bucket_origin,
viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS
)
}
)
// Create a Distribution with additional behaviors at creation time.
Bucket myBucket;
S3Origin bucketOrigin = new S3Origin(myBucket);
Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder()
.origin(bucketOrigin)
.allowedMethods(AllowedMethods.ALLOW_ALL)
.viewerProtocolPolicy(ViewerProtocolPolicy.REDIRECT_TO_HTTPS)
.build())
.additionalBehaviors(Map.of(
"/images/*.jpg", BehaviorOptions.builder()
.origin(bucketOrigin)
.viewerProtocolPolicy(ViewerProtocolPolicy.REDIRECT_TO_HTTPS)
.build()))
.build();
// Create a Distribution with additional behaviors at creation time.
Bucket myBucket;
var bucketOrigin = new S3Origin(myBucket);
new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = bucketOrigin,
AllowedMethods = AllowedMethods.ALLOW_ALL,
ViewerProtocolPolicy = ViewerProtocolPolicy.REDIRECT_TO_HTTPS
},
AdditionalBehaviors = new Dictionary<string, BehaviorOptions> {
{ "/images/*.jpg", new BehaviorOptions {
Origin = bucketOrigin,
ViewerProtocolPolicy = ViewerProtocolPolicy.REDIRECT_TO_HTTPS
} }
}
});
// Create a Distribution with additional behaviors at creation time.
var myBucket Bucket
bucketOrigin := origins.NewS3Origin(myBucket)
cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: bucketOrigin,
AllowedMethods: cloudfront.AllowedMethods_ALLOW_ALL(),
ViewerProtocolPolicy: cloudfront.ViewerProtocolPolicy_REDIRECT_TO_HTTPS,
},
AdditionalBehaviors: map[string]BehaviorOptions{
"/images/*.jpg": &BehaviorOptions{
"origin": bucketOrigin,
"viewerProtocolPolicy": cloudfront.ViewerProtocolPolicy_REDIRECT_TO_HTTPS,
},
},
})
Viewer Protocol Policy
Each behavior controls whether viewers may reach it over plaintext HTTP through its viewerProtocolPolicy. By default a behavior uses ViewerProtocolPolicy.ALLOW_ALL, which accepts both HTTP and HTTPS.
AWS recommends redirecting viewers to HTTPS, and AWS Security Hub control CloudFront.3 fails a distribution when the default behavior or any additional behavior uses allow-all. Enable the @aws-cdk/aws-cloudfront:defaultViewerProtocolPolicyRedirectToHttps feature flag to default every behavior to ViewerProtocolPolicy.REDIRECT_TO_HTTPS instead:
{
"context": {
"@aws-cdk/aws-cloudfront:defaultViewerProtocolPolicyRedirectToHttps": true
}
}
The flag applies to the default behavior, to additionalBehaviors, and to behaviors added later with addBehavior(). Projects created by cdk init enable it automatically; existing apps keep ALLOW_ALL until they opt in.
An explicit viewerProtocolPolicy always wins over the flag, so an individual behavior can opt back out:
declare const myBucket: s3.Bucket;
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: {
origin: origins.S3BucketOrigin.withOriginAccessControl(myBucket),
// Keeps accepting plaintext HTTP even when the feature flag is enabled.
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.ALLOW_ALL,
},
});
# my_bucket: s3.Bucket
cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.S3BucketOrigin.with_origin_access_control(my_bucket),
# Keeps accepting plaintext HTTP even when the feature flag is enabled.
viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.ALLOW_ALL
)
)
Bucket myBucket;
Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder()
.origin(S3BucketOrigin.withOriginAccessControl(myBucket))
// Keeps accepting plaintext HTTP even when the feature flag is enabled.
.viewerProtocolPolicy(ViewerProtocolPolicy.ALLOW_ALL)
.build())
.build();
Bucket myBucket;
new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = S3BucketOrigin.WithOriginAccessControl(myBucket),
// Keeps accepting plaintext HTTP even when the feature flag is enabled.
ViewerProtocolPolicy = ViewerProtocolPolicy.ALLOW_ALL
}
});
var myBucket Bucket
cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.S3BucketOrigin_WithOriginAccessControl(myBucket),
// Keeps accepting plaintext HTTP even when the feature flag is enabled.
ViewerProtocolPolicy: cloudfront.ViewerProtocolPolicy_ALLOW_ALL,
},
})
Note that REDIRECT_TO_HTTPS answers an HTTP request with an HTTP 301 redirect, which the viewer then follows with a second request; that additional request is billable. To reject plaintext HTTP outright rather than redirecting it, use ViewerProtocolPolicy.HTTPS_ONLY.
Attaching WAF Web Acls
You can attach the AWS WAF web ACL to a CloudFront distribution.
To specify a web ACL created using the latest version of AWS WAF, use the ACL ARN, for example arn:aws:wafv2:us-east-1:123456789012:global/webacl/ExampleWebACL/473e64fd-f30b-4765-81a0-62ad96dd167a. The web ACL must be in the us-east-1 region.
To specify a web ACL created using AWS WAF Classic, use the ACL ID, for example 473e64fd-f30b-4765-81a0-62ad96dd167a.
declare const bucketOrigin: origins.S3Origin;
declare const webAcl: wafv2.CfnWebACL;
const distribution = new cloudfront.Distribution(this, 'Distribution', {
defaultBehavior: { origin: bucketOrigin },
webAclId: webAcl.attrArn,
});
# bucket_origin: origins.S3Origin
# web_acl: wafv2.CfnWebACL
distribution = cloudfront.Distribution(self, "Distribution",
default_behavior=cloudfront.BehaviorOptions(origin=bucket_origin),
web_acl_id=web_acl.attr_arn
)
S3Origin bucketOrigin;
CfnWebACL webAcl;
Distribution distribution = Distribution.Builder.create(this, "Distribution")
.defaultBehavior(BehaviorOptions.builder().origin(bucketOrigin).build())
.webAclId(webAcl.getAttrArn())
.build();
S3Origin bucketOrigin;
CfnWebACL webAcl;
var distribution = new Distribution(this, "Distribution", new DistributionProps {
DefaultBehavior = new BehaviorOptions { Origin = bucketOrigin },
WebAclId = webAcl.AttrArn
});
var bucketOrigin S3Origin
var webAcl CfnWebACL
distribution := cloudfront.NewDistribution(this, jsii.String("Distribution"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: bucketOrigin,
},
WebAclId: webAcl.attrArn,
})
You can also attach a web ACL to a distribution after creation.
declare const bucketOrigin: origins.S3Origin;
declare const webAcl: wafv2.CfnWebACL;
const distribution = new cloudfront.Distribution(this, 'Distribution', {
defaultBehavior: { origin: bucketOrigin },
});
distribution.attachWebAclId(webAcl.attrArn);
# bucket_origin: origins.S3Origin
# web_acl: wafv2.CfnWebACL
distribution = cloudfront.Distribution(self, "Distribution",
default_behavior=cloudfront.BehaviorOptions(origin=bucket_origin)
)
distribution.attach_web_acl_id(web_acl.attr_arn)
S3Origin bucketOrigin;
CfnWebACL webAcl;
Distribution distribution = Distribution.Builder.create(this, "Distribution")
.defaultBehavior(BehaviorOptions.builder().origin(bucketOrigin).build())
.build();
distribution.attachWebAclId(webAcl.getAttrArn());
S3Origin bucketOrigin;
CfnWebACL webAcl;
var distribution = new Distribution(this, "Distribution", new DistributionProps {
DefaultBehavior = new BehaviorOptions { Origin = bucketOrigin }
});
distribution.AttachWebAclId(webAcl.AttrArn);
var bucketOrigin S3Origin
var webAcl CfnWebACL
distribution := cloudfront.NewDistribution(this, jsii.String("Distribution"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: bucketOrigin,
},
})
distribution.AttachWebAclId(webAcl.attrArn)
Customizing Cache Keys and TTLs with Cache Policies
You can use a cache policy to improve your cache hit ratio by controlling the values (URL query strings, HTTP headers, and cookies) that are included in the cache key, and/or adjusting how long items remain in the cache via the time-to-live (TTL) settings. CloudFront provides some predefined cache policies, known as managed policies, for common use cases. You can use these managed policies, or you can create your own cache policy that’s specific to your needs. See <https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html> for more details.
// Using an existing cache policy for a Distribution
declare const bucketOrigin: origins.S3Origin;
new cloudfront.Distribution(this, 'myDistManagedPolicy', {
defaultBehavior: {
origin: bucketOrigin,
cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED,
},
});
# Using an existing cache policy for a Distribution
# bucket_origin: origins.S3Origin
cloudfront.Distribution(self, "myDistManagedPolicy",
default_behavior=cloudfront.BehaviorOptions(
origin=bucket_origin,
cache_policy=cloudfront.CachePolicy.CACHING_OPTIMIZED
)
)
// Using an existing cache policy for a Distribution
S3Origin bucketOrigin;
Distribution.Builder.create(this, "myDistManagedPolicy")
.defaultBehavior(BehaviorOptions.builder()
.origin(bucketOrigin)
.cachePolicy(CachePolicy.CACHING_OPTIMIZED)
.build())
.build();
// Using an existing cache policy for a Distribution
S3Origin bucketOrigin;
new Distribution(this, "myDistManagedPolicy", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = bucketOrigin,
CachePolicy = CachePolicy.CACHING_OPTIMIZED
}
});
// Using an existing cache policy for a Distribution
var bucketOrigin S3Origin
cloudfront.NewDistribution(this, jsii.String("myDistManagedPolicy"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: bucketOrigin,
CachePolicy: cloudfront.CachePolicy_CACHING_OPTIMIZED(),
},
})
// Creating a custom cache policy for a Distribution -- all parameters optional
declare const bucketOrigin: origins.S3Origin;
const myCachePolicy = new cloudfront.CachePolicy(this, 'myCachePolicy', {
cachePolicyName: 'MyPolicy',
comment: 'A default policy',
defaultTtl: Duration.days(2),
minTtl: Duration.minutes(1),
maxTtl: Duration.days(10),
cookieBehavior: cloudfront.CacheCookieBehavior.all(),
headerBehavior: cloudfront.CacheHeaderBehavior.allowList('X-CustomHeader'),
queryStringBehavior: cloudfront.CacheQueryStringBehavior.denyList('username'),
enableAcceptEncodingGzip: true,
enableAcceptEncodingBrotli: true,
});
new cloudfront.Distribution(this, 'myDistCustomPolicy', {
defaultBehavior: {
origin: bucketOrigin,
cachePolicy: myCachePolicy,
},
});
# Creating a custom cache policy for a Distribution -- all parameters optional
# bucket_origin: origins.S3Origin
my_cache_policy = cloudfront.CachePolicy(self, "myCachePolicy",
cache_policy_name="MyPolicy",
comment="A default policy",
default_ttl=Duration.days(2),
min_ttl=Duration.minutes(1),
max_ttl=Duration.days(10),
cookie_behavior=cloudfront.CacheCookieBehavior.all(),
header_behavior=cloudfront.CacheHeaderBehavior.allow_list("X-CustomHeader"),
query_string_behavior=cloudfront.CacheQueryStringBehavior.deny_list("username"),
enable_accept_encoding_gzip=True,
enable_accept_encoding_brotli=True
)
cloudfront.Distribution(self, "myDistCustomPolicy",
default_behavior=cloudfront.BehaviorOptions(
origin=bucket_origin,
cache_policy=my_cache_policy
)
)
// Creating a custom cache policy for a Distribution -- all parameters optional
S3Origin bucketOrigin;
CachePolicy myCachePolicy = CachePolicy.Builder.create(this, "myCachePolicy")
.cachePolicyName("MyPolicy")
.comment("A default policy")
.defaultTtl(Duration.days(2))
.minTtl(Duration.minutes(1))
.maxTtl(Duration.days(10))
.cookieBehavior(CacheCookieBehavior.all())
.headerBehavior(CacheHeaderBehavior.allowList("X-CustomHeader"))
.queryStringBehavior(CacheQueryStringBehavior.denyList("username"))
.enableAcceptEncodingGzip(true)
.enableAcceptEncodingBrotli(true)
.build();
Distribution.Builder.create(this, "myDistCustomPolicy")
.defaultBehavior(BehaviorOptions.builder()
.origin(bucketOrigin)
.cachePolicy(myCachePolicy)
.build())
.build();
// Creating a custom cache policy for a Distribution -- all parameters optional
S3Origin bucketOrigin;
var myCachePolicy = new CachePolicy(this, "myCachePolicy", new CachePolicyProps {
CachePolicyName = "MyPolicy",
Comment = "A default policy",
DefaultTtl = Duration.Days(2),
MinTtl = Duration.Minutes(1),
MaxTtl = Duration.Days(10),
CookieBehavior = CacheCookieBehavior.All(),
HeaderBehavior = CacheHeaderBehavior.AllowList("X-CustomHeader"),
QueryStringBehavior = CacheQueryStringBehavior.DenyList("username"),
EnableAcceptEncodingGzip = true,
EnableAcceptEncodingBrotli = true
});
new Distribution(this, "myDistCustomPolicy", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = bucketOrigin,
CachePolicy = myCachePolicy
}
});
// Creating a custom cache policy for a Distribution -- all parameters optional
var bucketOrigin S3Origin
myCachePolicy := cloudfront.NewCachePolicy(this, jsii.String("myCachePolicy"), &CachePolicyProps{
CachePolicyName: jsii.String("MyPolicy"),
Comment: jsii.String("A default policy"),
DefaultTtl: awscdk.Duration_Days(jsii.Number(2)),
MinTtl: awscdk.Duration_Minutes(jsii.Number(1)),
MaxTtl: awscdk.Duration_*Days(jsii.Number(10)),
CookieBehavior: cloudfront.CacheCookieBehavior_All(),
HeaderBehavior: cloudfront.CacheHeaderBehavior_AllowList(jsii.String("X-CustomHeader")),
QueryStringBehavior: cloudfront.CacheQueryStringBehavior_DenyList(jsii.String("username")),
EnableAcceptEncodingGzip: jsii.Boolean(true),
EnableAcceptEncodingBrotli: jsii.Boolean(true),
})
cloudfront.NewDistribution(this, jsii.String("myDistCustomPolicy"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: bucketOrigin,
CachePolicy: myCachePolicy,
},
})
Customizing Origin Requests with Origin Request Policies
When CloudFront makes a request to an origin, the URL path, request body (if present), and a few standard headers are included. Other information from the viewer request, such as URL query strings, HTTP headers, and cookies, is not included in the origin request by default. You can use an origin request policy to control the information that’s included in an origin request. CloudFront provides some predefined origin request policies, known as managed policies, for common use cases. You can use these managed policies, or you can create your own origin request policy that’s specific to your needs. See <https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html> for more details.
// Using an existing origin request policy for a Distribution
declare const bucketOrigin: origins.S3Origin;
new cloudfront.Distribution(this, 'myDistManagedPolicy', {
defaultBehavior: {
origin: bucketOrigin,
originRequestPolicy: cloudfront.OriginRequestPolicy.CORS_S3_ORIGIN,
},
});
# Using an existing origin request policy for a Distribution
# bucket_origin: origins.S3Origin
cloudfront.Distribution(self, "myDistManagedPolicy",
default_behavior=cloudfront.BehaviorOptions(
origin=bucket_origin,
origin_request_policy=cloudfront.OriginRequestPolicy.CORS_S3_ORIGIN
)
)
// Using an existing origin request policy for a Distribution
S3Origin bucketOrigin;
Distribution.Builder.create(this, "myDistManagedPolicy")
.defaultBehavior(BehaviorOptions.builder()
.origin(bucketOrigin)
.originRequestPolicy(OriginRequestPolicy.CORS_S3_ORIGIN)
.build())
.build();
// Using an existing origin request policy for a Distribution
S3Origin bucketOrigin;
new Distribution(this, "myDistManagedPolicy", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = bucketOrigin,
OriginRequestPolicy = OriginRequestPolicy.CORS_S3_ORIGIN
}
});
// Using an existing origin request policy for a Distribution
var bucketOrigin S3Origin
cloudfront.NewDistribution(this, jsii.String("myDistManagedPolicy"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: bucketOrigin,
OriginRequestPolicy: cloudfront.OriginRequestPolicy_CORS_S3_ORIGIN(),
},
})
// Creating a custom origin request policy for a Distribution -- all parameters optional
declare const bucketOrigin: origins.S3Origin;
const myOriginRequestPolicy = new cloudfront.OriginRequestPolicy(this, 'OriginRequestPolicy', {
originRequestPolicyName: 'MyPolicy',
comment: 'A default policy',
cookieBehavior: cloudfront.OriginRequestCookieBehavior.none(),
headerBehavior: cloudfront.OriginRequestHeaderBehavior.all('CloudFront-Is-Android-Viewer'),
queryStringBehavior: cloudfront.OriginRequestQueryStringBehavior.allowList('username'),
});
new cloudfront.Distribution(this, 'myDistCustomPolicy', {
defaultBehavior: {
origin: bucketOrigin,
originRequestPolicy: myOriginRequestPolicy,
},
});
# Creating a custom origin request policy for a Distribution -- all parameters optional
# bucket_origin: origins.S3Origin
my_origin_request_policy = cloudfront.OriginRequestPolicy(self, "OriginRequestPolicy",
origin_request_policy_name="MyPolicy",
comment="A default policy",
cookie_behavior=cloudfront.OriginRequestCookieBehavior.none(),
header_behavior=cloudfront.OriginRequestHeaderBehavior.all("CloudFront-Is-Android-Viewer"),
query_string_behavior=cloudfront.OriginRequestQueryStringBehavior.allow_list("username")
)
cloudfront.Distribution(self, "myDistCustomPolicy",
default_behavior=cloudfront.BehaviorOptions(
origin=bucket_origin,
origin_request_policy=my_origin_request_policy
)
)
// Creating a custom origin request policy for a Distribution -- all parameters optional
S3Origin bucketOrigin;
OriginRequestPolicy myOriginRequestPolicy = OriginRequestPolicy.Builder.create(this, "OriginRequestPolicy")
.originRequestPolicyName("MyPolicy")
.comment("A default policy")
.cookieBehavior(OriginRequestCookieBehavior.none())
.headerBehavior(OriginRequestHeaderBehavior.all("CloudFront-Is-Android-Viewer"))
.queryStringBehavior(OriginRequestQueryStringBehavior.allowList("username"))
.build();
Distribution.Builder.create(this, "myDistCustomPolicy")
.defaultBehavior(BehaviorOptions.builder()
.origin(bucketOrigin)
.originRequestPolicy(myOriginRequestPolicy)
.build())
.build();
// Creating a custom origin request policy for a Distribution -- all parameters optional
S3Origin bucketOrigin;
var myOriginRequestPolicy = new OriginRequestPolicy(this, "OriginRequestPolicy", new OriginRequestPolicyProps {
OriginRequestPolicyName = "MyPolicy",
Comment = "A default policy",
CookieBehavior = OriginRequestCookieBehavior.None(),
HeaderBehavior = OriginRequestHeaderBehavior.All("CloudFront-Is-Android-Viewer"),
QueryStringBehavior = OriginRequestQueryStringBehavior.AllowList("username")
});
new Distribution(this, "myDistCustomPolicy", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = bucketOrigin,
OriginRequestPolicy = myOriginRequestPolicy
}
});
// Creating a custom origin request policy for a Distribution -- all parameters optional
var bucketOrigin S3Origin
myOriginRequestPolicy := cloudfront.NewOriginRequestPolicy(this, jsii.String("OriginRequestPolicy"), &OriginRequestPolicyProps{
OriginRequestPolicyName: jsii.String("MyPolicy"),
Comment: jsii.String("A default policy"),
CookieBehavior: cloudfront.OriginRequestCookieBehavior_None(),
HeaderBehavior: cloudfront.OriginRequestHeaderBehavior_All(jsii.String("CloudFront-Is-Android-Viewer")),
QueryStringBehavior: cloudfront.OriginRequestQueryStringBehavior_AllowList(jsii.String("username")),
})
cloudfront.NewDistribution(this, jsii.String("myDistCustomPolicy"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: bucketOrigin,
OriginRequestPolicy: myOriginRequestPolicy,
},
})
Customizing Response Headers with Response Headers Policies
You can configure CloudFront to add one or more HTTP headers to the responses that it sends to viewers (web browsers or other clients), without making any changes to the origin or writing any code. To specify the headers that CloudFront adds to HTTP responses, you use a response headers policy. CloudFront adds the headers regardless of whether it serves the object from the cache or has to retrieve the object from the origin. If the origin response includes one or more of the headers that’s in a response headers policy, the policy can specify whether CloudFront uses the header it received from the origin or overwrites it with the one in the policy. See <https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/adding-response-headers.html>
NOTE
If xssProtection reportUri is specified, then modeBlock cannot be set to true.
// Using an existing managed response headers policy
declare const bucketOrigin: origins.S3Origin;
new cloudfront.Distribution(this, 'myDistManagedPolicy', {
defaultBehavior: {
origin: bucketOrigin,
responseHeadersPolicy: cloudfront.ResponseHeadersPolicy.CORS_ALLOW_ALL_ORIGINS,
},
});
// Creating a custom response headers policy -- all parameters optional
const myResponseHeadersPolicy = new cloudfront.ResponseHeadersPolicy(this, 'ResponseHeadersPolicy', {
responseHeadersPolicyName: 'MyPolicy',
comment: 'A default policy',
corsBehavior: {
accessControlAllowCredentials: false,
accessControlAllowHeaders: ['X-Custom-Header-1', 'X-Custom-Header-2'],
accessControlAllowMethods: ['GET', 'POST'],
accessControlAllowOrigins: ['*'],
accessControlExposeHeaders: ['X-Custom-Header-1', 'X-Custom-Header-2'],
accessControlMaxAge: Duration.seconds(600),
originOverride: true,
},
customHeadersBehavior: {
customHeaders: [
{ header: 'X-Amz-Date', value: 'some-value', override: true },
{ header: 'X-Amz-Security-Token', value: 'some-value', override: false },
],
},
securityHeadersBehavior: {
contentSecurityPolicy: { contentSecurityPolicy: 'default-src https:;', override: true },
contentTypeOptions: { override: true },
frameOptions: { frameOption: cloudfront.HeadersFrameOption.DENY, override: true },
referrerPolicy: { referrerPolicy: cloudfront.HeadersReferrerPolicy.NO_REFERRER, override: true },
strictTransportSecurity: { accessControlMaxAge: Duration.seconds(600), includeSubdomains: true, override: true },
xssProtection: { protection: true, modeBlock: false, reportUri: 'https://example.com/csp-report', override: true },
},
removeHeaders: ['Server'],
serverTimingSamplingRate: 50,
});
new cloudfront.Distribution(this, 'myDistCustomPolicy', {
defaultBehavior: {
origin: bucketOrigin,
responseHeadersPolicy: myResponseHeadersPolicy,
},
});
# Using an existing managed response headers policy
# bucket_origin: origins.S3Origin
cloudfront.Distribution(self, "myDistManagedPolicy",
default_behavior=cloudfront.BehaviorOptions(
origin=bucket_origin,
response_headers_policy=cloudfront.ResponseHeadersPolicy.CORS_ALLOW_ALL_ORIGINS
)
)
# Creating a custom response headers policy -- all parameters optional
my_response_headers_policy = cloudfront.ResponseHeadersPolicy(self, "ResponseHeadersPolicy",
response_headers_policy_name="MyPolicy",
comment="A default policy",
cors_behavior=cloudfront.ResponseHeadersCorsBehavior(
access_control_allow_credentials=False,
access_control_allow_headers=["X-Custom-Header-1", "X-Custom-Header-2"],
access_control_allow_methods=["GET", "POST"],
access_control_allow_origins=["*"],
access_control_expose_headers=["X-Custom-Header-1", "X-Custom-Header-2"],
access_control_max_age=Duration.seconds(600),
origin_override=True
),
custom_headers_behavior=cloudfront.ResponseCustomHeadersBehavior(
custom_headers=[cloudfront.ResponseCustomHeader(header="X-Amz-Date", value="some-value", override=True), cloudfront.ResponseCustomHeader(header="X-Amz-Security-Token", value="some-value", override=False)
]
),
security_headers_behavior=cloudfront.ResponseSecurityHeadersBehavior(
content_security_policy=cloudfront.ResponseHeadersContentSecurityPolicy(content_security_policy="default-src https:;", override=True),
content_type_options=cloudfront.ResponseHeadersContentTypeOptions(override=True),
frame_options=cloudfront.ResponseHeadersFrameOptions(frame_option=cloudfront.HeadersFrameOption.DENY, override=True),
referrer_policy=cloudfront.ResponseHeadersReferrerPolicy(referrer_policy=cloudfront.HeadersReferrerPolicy.NO_REFERRER, override=True),
strict_transport_security=cloudfront.ResponseHeadersStrictTransportSecurity(access_control_max_age=Duration.seconds(600), include_subdomains=True, override=True),
xss_protection=cloudfront.ResponseHeadersXSSProtection(protection=True, mode_block=False, report_uri="https://example.com/csp-report", override=True)
),
remove_headers=["Server"],
server_timing_sampling_rate=50
)
cloudfront.Distribution(self, "myDistCustomPolicy",
default_behavior=cloudfront.BehaviorOptions(
origin=bucket_origin,
response_headers_policy=my_response_headers_policy
)
)
// Using an existing managed response headers policy
S3Origin bucketOrigin;
Distribution.Builder.create(this, "myDistManagedPolicy")
.defaultBehavior(BehaviorOptions.builder()
.origin(bucketOrigin)
.responseHeadersPolicy(ResponseHeadersPolicy.CORS_ALLOW_ALL_ORIGINS)
.build())
.build();
// Creating a custom response headers policy -- all parameters optional
ResponseHeadersPolicy myResponseHeadersPolicy = ResponseHeadersPolicy.Builder.create(this, "ResponseHeadersPolicy")
.responseHeadersPolicyName("MyPolicy")
.comment("A default policy")
.corsBehavior(ResponseHeadersCorsBehavior.builder()
.accessControlAllowCredentials(false)
.accessControlAllowHeaders(List.of("X-Custom-Header-1", "X-Custom-Header-2"))
.accessControlAllowMethods(List.of("GET", "POST"))
.accessControlAllowOrigins(List.of("*"))
.accessControlExposeHeaders(List.of("X-Custom-Header-1", "X-Custom-Header-2"))
.accessControlMaxAge(Duration.seconds(600))
.originOverride(true)
.build())
.customHeadersBehavior(ResponseCustomHeadersBehavior.builder()
.customHeaders(List.of(ResponseCustomHeader.builder().header("X-Amz-Date").value("some-value").override(true).build(), ResponseCustomHeader.builder().header("X-Amz-Security-Token").value("some-value").override(false).build()))
.build())
.securityHeadersBehavior(ResponseSecurityHeadersBehavior.builder()
.contentSecurityPolicy(ResponseHeadersContentSecurityPolicy.builder().contentSecurityPolicy("default-src https:;").override(true).build())
.contentTypeOptions(ResponseHeadersContentTypeOptions.builder().override(true).build())
.frameOptions(ResponseHeadersFrameOptions.builder().frameOption(HeadersFrameOption.DENY).override(true).build())
.referrerPolicy(ResponseHeadersReferrerPolicy.builder().referrerPolicy(HeadersReferrerPolicy.NO_REFERRER).override(true).build())
.strictTransportSecurity(ResponseHeadersStrictTransportSecurity.builder().accessControlMaxAge(Duration.seconds(600)).includeSubdomains(true).override(true).build())
.xssProtection(ResponseHeadersXSSProtection.builder().protection(true).modeBlock(false).reportUri("https://example.com/csp-report").override(true).build())
.build())
.removeHeaders(List.of("Server"))
.serverTimingSamplingRate(50)
.build();
Distribution.Builder.create(this, "myDistCustomPolicy")
.defaultBehavior(BehaviorOptions.builder()
.origin(bucketOrigin)
.responseHeadersPolicy(myResponseHeadersPolicy)
.build())
.build();
// Using an existing managed response headers policy
S3Origin bucketOrigin;
new Distribution(this, "myDistManagedPolicy", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = bucketOrigin,
ResponseHeadersPolicy = ResponseHeadersPolicy.CORS_ALLOW_ALL_ORIGINS
}
});
// Creating a custom response headers policy -- all parameters optional
var myResponseHeadersPolicy = new ResponseHeadersPolicy(this, "ResponseHeadersPolicy", new ResponseHeadersPolicyProps {
ResponseHeadersPolicyName = "MyPolicy",
Comment = "A default policy",
CorsBehavior = new ResponseHeadersCorsBehavior {
AccessControlAllowCredentials = false,
AccessControlAllowHeaders = new [] { "X-Custom-Header-1", "X-Custom-Header-2" },
AccessControlAllowMethods = new [] { "GET", "POST" },
AccessControlAllowOrigins = new [] { "*" },
AccessControlExposeHeaders = new [] { "X-Custom-Header-1", "X-Custom-Header-2" },
AccessControlMaxAge = Duration.Seconds(600),
OriginOverride = true
},
CustomHeadersBehavior = new ResponseCustomHeadersBehavior {
CustomHeaders = new [] { new ResponseCustomHeader { Header = "X-Amz-Date", Value = "some-value", Override = true }, new ResponseCustomHeader { Header = "X-Amz-Security-Token", Value = "some-value", Override = false } }
},
SecurityHeadersBehavior = new ResponseSecurityHeadersBehavior {
ContentSecurityPolicy = new ResponseHeadersContentSecurityPolicy { ContentSecurityPolicy = "default-src https:;", Override = true },
ContentTypeOptions = new ResponseHeadersContentTypeOptions { Override = true },
FrameOptions = new ResponseHeadersFrameOptions { FrameOption = HeadersFrameOption.DENY, Override = true },
ReferrerPolicy = new ResponseHeadersReferrerPolicy { ReferrerPolicy = HeadersReferrerPolicy.NO_REFERRER, Override = true },
StrictTransportSecurity = new ResponseHeadersStrictTransportSecurity { AccessControlMaxAge = Duration.Seconds(600), IncludeSubdomains = true, Override = true },
XssProtection = new ResponseHeadersXSSProtection { Protection = true, ModeBlock = false, ReportUri = "https://example.com/csp-report", Override = true }
},
RemoveHeaders = new [] { "Server" },
ServerTimingSamplingRate = 50
});
new Distribution(this, "myDistCustomPolicy", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = bucketOrigin,
ResponseHeadersPolicy = myResponseHeadersPolicy
}
});
// Using an existing managed response headers policy
var bucketOrigin S3Origin
cloudfront.NewDistribution(this, jsii.String("myDistManagedPolicy"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: bucketOrigin,
ResponseHeadersPolicy: cloudfront.ResponseHeadersPolicy_CORS_ALLOW_ALL_ORIGINS(),
},
})
// Creating a custom response headers policy -- all parameters optional
myResponseHeadersPolicy := cloudfront.NewResponseHeadersPolicy(this, jsii.String("ResponseHeadersPolicy"), &ResponseHeadersPolicyProps{
ResponseHeadersPolicyName: jsii.String("MyPolicy"),
Comment: jsii.String("A default policy"),
CorsBehavior: &ResponseHeadersCorsBehavior{
AccessControlAllowCredentials: jsii.Boolean(false),
AccessControlAllowHeaders: []*string{
jsii.String("X-Custom-Header-1"),
jsii.String("X-Custom-Header-2"),
},
AccessControlAllowMethods: []*string{
jsii.String("GET"),
jsii.String("POST"),
},
AccessControlAllowOrigins: []*string{
jsii.String("*"),
},
AccessControlExposeHeaders: []*string{
jsii.String("X-Custom-Header-1"),
jsii.String("X-Custom-Header-2"),
},
AccessControlMaxAge: awscdk.Duration_Seconds(jsii.Number(600)),
OriginOverride: jsii.Boolean(true),
},
CustomHeadersBehavior: &ResponseCustomHeadersBehavior{
CustomHeaders: []ResponseCustomHeader{
&ResponseCustomHeader{
Header: jsii.String("X-Amz-Date"),
Value: jsii.String("some-value"),
Override: jsii.Boolean(true),
},
&ResponseCustomHeader{
Header: jsii.String("X-Amz-Security-Token"),
Value: jsii.String("some-value"),
Override: jsii.Boolean(false),
},
},
},
SecurityHeadersBehavior: &ResponseSecurityHeadersBehavior{
ContentSecurityPolicy: &ResponseHeadersContentSecurityPolicy{
ContentSecurityPolicy: jsii.String("default-src https:;"),
Override: jsii.Boolean(true),
},
ContentTypeOptions: &ResponseHeadersContentTypeOptions{
Override: jsii.Boolean(true),
},
FrameOptions: &ResponseHeadersFrameOptions{
FrameOption: cloudfront.HeadersFrameOption_DENY,
Override: jsii.Boolean(true),
},
ReferrerPolicy: &ResponseHeadersReferrerPolicy{
ReferrerPolicy: cloudfront.HeadersReferrerPolicy_NO_REFERRER,
Override: jsii.Boolean(true),
},
StrictTransportSecurity: &ResponseHeadersStrictTransportSecurity{
AccessControlMaxAge: awscdk.Duration_*Seconds(jsii.Number(600)),
IncludeSubdomains: jsii.Boolean(true),
Override: jsii.Boolean(true),
},
XssProtection: &ResponseHeadersXSSProtection{
Protection: jsii.Boolean(true),
ModeBlock: jsii.Boolean(false),
ReportUri: jsii.String("https://example.com/csp-report"),
Override: jsii.Boolean(true),
},
},
RemoveHeaders: []*string{
jsii.String("Server"),
},
ServerTimingSamplingRate: jsii.Number(50),
})
cloudfront.NewDistribution(this, jsii.String("myDistCustomPolicy"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: bucketOrigin,
ResponseHeadersPolicy: myResponseHeadersPolicy,
},
})
Validating signed URLs or signed cookies with Trusted Key Groups
CloudFront Distribution supports validating signed URLs or signed cookies using key groups. When a cache behavior contains trusted key groups, CloudFront requires signed URLs or signed cookies for all requests that match the cache behavior.
// Validating signed URLs or signed cookies with Trusted Key Groups
// public key in PEM format
declare const publicKey: string;
const pubKey = new cloudfront.PublicKey(this, 'MyPubKey', {
encodedKey: publicKey,
});
const keyGroup = new cloudfront.KeyGroup(this, 'MyKeyGroup', {
items: [
pubKey,
],
});
new cloudfront.Distribution(this, 'Dist', {
defaultBehavior: {
origin: new origins.HttpOrigin('www.example.com'),
trustedKeyGroups: [
keyGroup,
],
},
});
# Validating signed URLs or signed cookies with Trusted Key Groups
# public key in PEM format
# public_key: str
pub_key = cloudfront.PublicKey(self, "MyPubKey",
encoded_key=public_key
)
key_group = cloudfront.KeyGroup(self, "MyKeyGroup",
items=[pub_key
]
)
cloudfront.Distribution(self, "Dist",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.HttpOrigin("www.example.com"),
trusted_key_groups=[key_group
]
)
)
// Validating signed URLs or signed cookies with Trusted Key Groups
// public key in PEM format
String publicKey;
PublicKey pubKey = PublicKey.Builder.create(this, "MyPubKey")
.encodedKey(publicKey)
.build();
KeyGroup keyGroup = KeyGroup.Builder.create(this, "MyKeyGroup")
.items(List.of(pubKey))
.build();
Distribution.Builder.create(this, "Dist")
.defaultBehavior(BehaviorOptions.builder()
.origin(new HttpOrigin("www.example.com"))
.trustedKeyGroups(List.of(keyGroup))
.build())
.build();
// Validating signed URLs or signed cookies with Trusted Key Groups
// public key in PEM format
string publicKey;
var pubKey = new PublicKey(this, "MyPubKey", new PublicKeyProps {
EncodedKey = publicKey
});
var keyGroup = new KeyGroup(this, "MyKeyGroup", new KeyGroupProps {
Items = new [] { pubKey }
});
new Distribution(this, "Dist", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = new HttpOrigin("www.example.com"),
TrustedKeyGroups = new [] { keyGroup }
}
});
// Validating signed URLs or signed cookies with Trusted Key Groups
// public key in PEM format
var publicKey string
pubKey := cloudfront.NewPublicKey(this, jsii.String("MyPubKey"), &PublicKeyProps{
EncodedKey: publicKey,
})
keyGroup := cloudfront.NewKeyGroup(this, jsii.String("MyKeyGroup"), &KeyGroupProps{
Items: []IPublicKeyRef{
pubKey,
},
})
cloudfront.NewDistribution(this, jsii.String("Dist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewHttpOrigin(jsii.String("www.example.com")),
TrustedKeyGroups: []IKeyGroupRef{
keyGroup,
},
},
})
Lambda@Edge
Lambda@Edge is an extension of AWS Lambda, a compute service that lets you execute functions that customize the content that CloudFront delivers. You can author Node.js or Python functions in the US East (N. Virginia) region, and then execute them in AWS locations globally that are closer to the viewer, without provisioning or managing servers. Lambda@Edge functions are associated with a specific behavior and event type. Lambda@Edge can be used to rewrite URLs, alter responses based on headers or cookies, or authorize requests based on headers or authorization tokens.
The following shows a Lambda@Edge function added to the default behavior and triggered on every request:
// A Lambda@Edge function added to default behavior of a Distribution
// and triggered on every request
const myFunc = new cloudfront.experimental.EdgeFunction(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_LATEST,
handler: 'index.handler',
code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
});
declare const myBucket: s3.Bucket;
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: {
origin: new origins.S3Origin(myBucket),
edgeLambdas: [
{
functionVersion: myFunc.currentVersion,
eventType: cloudfront.LambdaEdgeEventType.VIEWER_REQUEST,
}
],
},
});
# my_bucket: s3.Bucket
# A Lambda@Edge function added to default behavior of a Distribution
# and triggered on every request
my_func = cloudfront.experimental.EdgeFunction(self, "MyFunction",
runtime=lambda_.Runtime.NODEJS_LATEST,
handler="index.handler",
code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler"))
)
cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.S3Origin(my_bucket),
edge_lambdas=[cloudfront.EdgeLambda(
function_version=my_func.current_version,
event_type=cloudfront.LambdaEdgeEventType.VIEWER_REQUEST
)
]
)
)
Bucket myBucket;
// A Lambda@Edge function added to default behavior of a Distribution
// and triggered on every request
EdgeFunction myFunc = EdgeFunction.Builder.create(this, "MyFunction")
.runtime(Runtime.NODEJS_LATEST)
.handler("index.handler")
.code(Code.fromAsset(join(__dirname, "lambda-handler")))
.build();
Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder()
.origin(new S3Origin(myBucket))
.edgeLambdas(List.of(EdgeLambda.builder()
.functionVersion(myFunc.getCurrentVersion())
.eventType(LambdaEdgeEventType.VIEWER_REQUEST)
.build()))
.build())
.build();
Bucket myBucket;
// A Lambda@Edge function added to default behavior of a Distribution
// and triggered on every request
var myFunc = new Experimental.EdgeFunction(this, "MyFunction", new EdgeFunctionProps {
Runtime = Runtime.NODEJS_LATEST,
Handler = "index.handler",
Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});
new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = new S3Origin(myBucket),
EdgeLambdas = new [] { new EdgeLambda {
FunctionVersion = myFunc.CurrentVersion,
EventType = LambdaEdgeEventType.VIEWER_REQUEST
} }
}
});
var myBucket Bucket
// A Lambda@Edge function added to default behavior of a Distribution
// and triggered on every request
myFunc := experimental.NewEdgeFunction(this, jsii.String("MyFunction"), &EdgeFunctionProps{
Runtime: lambda.Runtime_NODEJS_LATEST(),
Handler: jsii.String("index.handler"),
Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
})
cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewS3Origin(myBucket),
EdgeLambdas: []EdgeLambda{
&EdgeLambda{
FunctionVersion: myFunc.currentVersion,
EventType: cloudfront.LambdaEdgeEventType_VIEWER_REQUEST,
},
},
},
})
Note: Lambda@Edge functions must be created in the
us-east-1region, regardless of the region of the CloudFront distribution and stack. To make it easier to request functions for Lambda@Edge, theEdgeFunctionconstruct can be used. TheEdgeFunctionconstruct will automatically request a function inus-east-1, regardless of the region of the current stack.EdgeFunctionhas the same interface asFunctionand can be created and used interchangeably. Please note that usingEdgeFunctionrequires that theus-east-1region has been bootstrapped. See <https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html> for more about bootstrapping regions.
If the stack is in us-east-1, a "normal" lambda.Function can be used instead of an EdgeFunction.
// Using a lambda Function instead of an EdgeFunction for stacks in `us-east-`.
const myFunc = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_LATEST,
handler: 'index.handler',
code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
});
# Using a lambda Function instead of an EdgeFunction for stacks in `us-east-`.
my_func = lambda_.Function(self, "MyFunction",
runtime=lambda_.Runtime.NODEJS_LATEST,
handler="index.handler",
code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler"))
)
// Using a lambda Function instead of an EdgeFunction for stacks in `us-east-`.
Function myFunc = Function.Builder.create(this, "MyFunction")
.runtime(Runtime.NODEJS_LATEST)
.handler("index.handler")
.code(Code.fromAsset(join(__dirname, "lambda-handler")))
.build();
// Using a lambda Function instead of an EdgeFunction for stacks in `us-east-`.
var myFunc = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_LATEST,
Handler = "index.handler",
Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});
// Using a lambda Function instead of an EdgeFunction for stacks in `us-east-`.
myFunc := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
Runtime: lambda.Runtime_NODEJS_LATEST(),
Handler: jsii.String("index.handler"),
Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
})
If the stack is not in us-east-1, and you need references from different applications on the same account, you can also set a specific stack ID for each Lambda@Edge.
// Setting stackIds for EdgeFunctions that can be referenced from different applications
// on the same account.
const myFunc1 = new cloudfront.experimental.EdgeFunction(this, 'MyFunction1', {
runtime: lambda.Runtime.NODEJS_LATEST,
handler: 'index.handler',
code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler1')),
stackId: 'edge-lambda-stack-id-1',
});
const myFunc2 = new cloudfront.experimental.EdgeFunction(this, 'MyFunction2', {
runtime: lambda.Runtime.NODEJS_LATEST,
handler: 'index.handler',
code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler2')),
stackId: 'edge-lambda-stack-id-2',
});
# Setting stackIds for EdgeFunctions that can be referenced from different applications
# on the same account.
my_func1 = cloudfront.experimental.EdgeFunction(self, "MyFunction1",
runtime=lambda_.Runtime.NODEJS_LATEST,
handler="index.handler",
code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler1")),
stack_id="edge-lambda-stack-id-1"
)
my_func2 = cloudfront.experimental.EdgeFunction(self, "MyFunction2",
runtime=lambda_.Runtime.NODEJS_LATEST,
handler="index.handler",
code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler2")),
stack_id="edge-lambda-stack-id-2"
)
// Setting stackIds for EdgeFunctions that can be referenced from different applications
// on the same account.
EdgeFunction myFunc1 = EdgeFunction.Builder.create(this, "MyFunction1")
.runtime(Runtime.NODEJS_LATEST)
.handler("index.handler")
.code(Code.fromAsset(join(__dirname, "lambda-handler1")))
.stackId("edge-lambda-stack-id-1")
.build();
EdgeFunction myFunc2 = EdgeFunction.Builder.create(this, "MyFunction2")
.runtime(Runtime.NODEJS_LATEST)
.handler("index.handler")
.code(Code.fromAsset(join(__dirname, "lambda-handler2")))
.stackId("edge-lambda-stack-id-2")
.build();
// Setting stackIds for EdgeFunctions that can be referenced from different applications
// on the same account.
var myFunc1 = new Experimental.EdgeFunction(this, "MyFunction1", new EdgeFunctionProps {
Runtime = Runtime.NODEJS_LATEST,
Handler = "index.handler",
Code = Code.FromAsset(Join(__dirname, "lambda-handler1")),
StackId = "edge-lambda-stack-id-1"
});
var myFunc2 = new Experimental.EdgeFunction(this, "MyFunction2", new EdgeFunctionProps {
Runtime = Runtime.NODEJS_LATEST,
Handler = "index.handler",
Code = Code.FromAsset(Join(__dirname, "lambda-handler2")),
StackId = "edge-lambda-stack-id-2"
});
// Setting stackIds for EdgeFunctions that can be referenced from different applications
// on the same account.
myFunc1 := experimental.NewEdgeFunction(this, jsii.String("MyFunction1"), &EdgeFunctionProps{
Runtime: lambda.Runtime_NODEJS_LATEST(),
Handler: jsii.String("index.handler"),
Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler1"))),
StackId: jsii.String("edge-lambda-stack-id-1"),
})
myFunc2 := experimental.NewEdgeFunction(this, jsii.String("MyFunction2"), &EdgeFunctionProps{
Runtime: lambda.Runtime_NODEJS_LATEST(),
Handler: jsii.String("index.handler"),
Code: lambda.Code_*FromAsset(path.join(__dirname, jsii.String("lambda-handler2"))),
StackId: jsii.String("edge-lambda-stack-id-2"),
})
Lambda@Edge functions can also be associated with additional behaviors, either at or after Distribution creation time.
// Associating a Lambda@Edge function with additional behaviors.
declare const myFunc: cloudfront.experimental.EdgeFunction;
// assigning at Distribution creation
declare const myBucket: s3.Bucket;
const myOrigin = new origins.S3Origin(myBucket);
const myDistribution = new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: myOrigin },
additionalBehaviors: {
'images/*': {
origin: myOrigin,
edgeLambdas: [
{
functionVersion: myFunc.currentVersion,
eventType: cloudfront.LambdaEdgeEventType.ORIGIN_REQUEST,
includeBody: true, // Optional - defaults to false
},
],
},
},
});
// assigning after creation
myDistribution.addBehavior('images/*', myOrigin, {
edgeLambdas: [
{
functionVersion: myFunc.currentVersion,
eventType: cloudfront.LambdaEdgeEventType.VIEWER_RESPONSE,
},
],
});
# Associating a Lambda@Edge function with additional behaviors.
# my_func: cloudfront.experimental.EdgeFunction
# assigning at Distribution creation
# my_bucket: s3.Bucket
my_origin = origins.S3Origin(my_bucket)
my_distribution = cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(origin=my_origin),
additional_behaviors={
"images/*": cloudfront.BehaviorOptions(
origin=my_origin,
edge_lambdas=[cloudfront.EdgeLambda(
function_version=my_func.current_version,
event_type=cloudfront.LambdaEdgeEventType.ORIGIN_REQUEST,
include_body=True
)
]
)
}
)
# assigning after creation
my_distribution.add_behavior("images/*", my_origin,
edge_lambdas=[cloudfront.EdgeLambda(
function_version=my_func.current_version,
event_type=cloudfront.LambdaEdgeEventType.VIEWER_RESPONSE
)
]
)
// Associating a Lambda@Edge function with additional behaviors.
EdgeFunction myFunc;
// assigning at Distribution creation
Bucket myBucket;
S3Origin myOrigin = new S3Origin(myBucket);
Distribution myDistribution = Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder().origin(myOrigin).build())
.additionalBehaviors(Map.of(
"images/*", BehaviorOptions.builder()
.origin(myOrigin)
.edgeLambdas(List.of(EdgeLambda.builder()
.functionVersion(myFunc.getCurrentVersion())
.eventType(LambdaEdgeEventType.ORIGIN_REQUEST)
.includeBody(true)
.build()))
.build()))
.build();
// assigning after creation
myDistribution.addBehavior("images/*", myOrigin, AddBehaviorOptions.builder()
.edgeLambdas(List.of(EdgeLambda.builder()
.functionVersion(myFunc.getCurrentVersion())
.eventType(LambdaEdgeEventType.VIEWER_RESPONSE)
.build()))
.build());
// Associating a Lambda@Edge function with additional behaviors.
EdgeFunction myFunc;
// assigning at Distribution creation
Bucket myBucket;
var myOrigin = new S3Origin(myBucket);
var myDistribution = new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions { Origin = myOrigin },
AdditionalBehaviors = new Dictionary<string, BehaviorOptions> {
{ "images/*", new BehaviorOptions {
Origin = myOrigin,
EdgeLambdas = new [] { new EdgeLambda {
FunctionVersion = myFunc.CurrentVersion,
EventType = LambdaEdgeEventType.ORIGIN_REQUEST,
IncludeBody = true
} }
} }
}
});
// assigning after creation
myDistribution.AddBehavior("images/*", myOrigin, new AddBehaviorOptions {
EdgeLambdas = new [] { new EdgeLambda {
FunctionVersion = myFunc.CurrentVersion,
EventType = LambdaEdgeEventType.VIEWER_RESPONSE
} }
});
// Associating a Lambda@Edge function with additional behaviors.
var myFunc EdgeFunction
// assigning at Distribution creation
var myBucket Bucket
myOrigin := origins.NewS3Origin(myBucket)
myDistribution := cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: myOrigin,
},
AdditionalBehaviors: map[string]BehaviorOptions{
"images/*": &BehaviorOptions{
"origin": myOrigin,
"edgeLambdas": []EdgeLambda{
&EdgeLambda{
"functionVersion": myFunc.currentVersion,
"eventType": cloudfront.LambdaEdgeEventType_ORIGIN_REQUEST,
"includeBody": jsii.Boolean(true),
},
},
},
},
})
// assigning after creation
myDistribution.AddBehavior(jsii.String("images/*"), myOrigin, &AddBehaviorOptions{
EdgeLambdas: []EdgeLambda{
&EdgeLambda{
FunctionVersion: myFunc.currentVersion,
EventType: cloudfront.LambdaEdgeEventType_VIEWER_RESPONSE,
},
},
})
Adding an existing Lambda@Edge function created in a different stack to a CloudFront distribution.
// Adding an existing Lambda@Edge function created in a different stack
// to a CloudFront distribution.
declare const s3Bucket: s3.Bucket;
const functionVersion = lambda.Version.fromVersionArn(this, 'Version', 'arn:aws:lambda:us-east-1:123456789012:function:functionName:1');
new cloudfront.Distribution(this, 'distro', {
defaultBehavior: {
origin: origins.S3BucketOrigin.withOriginAccessControl(s3Bucket),
edgeLambdas: [
{
functionVersion,
eventType: cloudfront.LambdaEdgeEventType.VIEWER_REQUEST,
},
],
},
});
# Adding an existing Lambda@Edge function created in a different stack
# to a CloudFront distribution.
# s3_bucket: s3.Bucket
function_version = lambda_.Version.from_version_arn(self, "Version", "arn:aws:lambda:us-east-1:123456789012:function:functionName:1")
cloudfront.Distribution(self, "distro",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.S3BucketOrigin.with_origin_access_control(s3_bucket),
edge_lambdas=[cloudfront.EdgeLambda(
function_version=function_version,
event_type=cloudfront.LambdaEdgeEventType.VIEWER_REQUEST
)
]
)
)
// Adding an existing Lambda@Edge function created in a different stack
// to a CloudFront distribution.
Bucket s3Bucket;
IVersion functionVersion = Version.fromVersionArn(this, "Version", "arn:aws:lambda:us-east-1:123456789012:function:functionName:1");
Distribution.Builder.create(this, "distro")
.defaultBehavior(BehaviorOptions.builder()
.origin(S3BucketOrigin.withOriginAccessControl(s3Bucket))
.edgeLambdas(List.of(EdgeLambda.builder()
.functionVersion(functionVersion)
.eventType(LambdaEdgeEventType.VIEWER_REQUEST)
.build()))
.build())
.build();
// Adding an existing Lambda@Edge function created in a different stack
// to a CloudFront distribution.
Bucket s3Bucket;
var functionVersion = Version.FromVersionArn(this, "Version", "arn:aws:lambda:us-east-1:123456789012:function:functionName:1");
new Distribution(this, "distro", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = S3BucketOrigin.WithOriginAccessControl(s3Bucket),
EdgeLambdas = new [] { new EdgeLambda {
FunctionVersion = functionVersion,
EventType = LambdaEdgeEventType.VIEWER_REQUEST
} }
}
});
// Adding an existing Lambda@Edge function created in a different stack
// to a CloudFront distribution.
var s3Bucket Bucket
functionVersion := lambda.Version_FromVersionArn(this, jsii.String("Version"), jsii.String("arn:aws:lambda:us-east-1:123456789012:function:functionName:1"))
cloudfront.NewDistribution(this, jsii.String("distro"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.S3BucketOrigin_WithOriginAccessControl(s3Bucket),
EdgeLambdas: []EdgeLambda{
&EdgeLambda{
FunctionVersion: *FunctionVersion,
EventType: cloudfront.LambdaEdgeEventType_VIEWER_REQUEST,
},
},
},
})
CloudFront Function
You can also deploy CloudFront functions and add them to a CloudFront distribution.
// Add a cloudfront Function to a Distribution
const cfFunction = new cloudfront.Function(this, 'Function', {
code: cloudfront.FunctionCode.fromInline('function handler(event) { return event.request }'),
runtime: cloudfront.FunctionRuntime.JS_2_0,
});
declare const s3Bucket: s3.Bucket;
new cloudfront.Distribution(this, 'distro', {
defaultBehavior: {
origin: new origins.S3Origin(s3Bucket),
functionAssociations: [{
function: cfFunction,
eventType: cloudfront.FunctionEventType.VIEWER_REQUEST,
}],
},
});
# s3_bucket: s3.Bucket
# Add a cloudfront Function to a Distribution
cf_function = cloudfront.Function(self, "Function",
code=cloudfront.FunctionCode.from_inline("function handler(event) { return event.request }"),
runtime=cloudfront.FunctionRuntime.JS_2_0
)
cloudfront.Distribution(self, "distro",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.S3Origin(s3_bucket),
function_associations=[cloudfront.FunctionAssociation(
function=cf_function,
event_type=cloudfront.FunctionEventType.VIEWER_REQUEST
)]
)
)
Bucket s3Bucket;
// Add a cloudfront Function to a Distribution
Function cfFunction = Function.Builder.create(this, "Function")
.code(FunctionCode.fromInline("function handler(event) { return event.request }"))
.runtime(FunctionRuntime.JS_2_0)
.build();
Distribution.Builder.create(this, "distro")
.defaultBehavior(BehaviorOptions.builder()
.origin(new S3Origin(s3Bucket))
.functionAssociations(List.of(FunctionAssociation.builder()
.function(cfFunction)
.eventType(FunctionEventType.VIEWER_REQUEST)
.build()))
.build())
.build();
Bucket s3Bucket;
// Add a cloudfront Function to a Distribution
var cfFunction = new Function(this, "Function", new FunctionProps {
Code = FunctionCode.FromInline("function handler(event) { return event.request }"),
Runtime = FunctionRuntime.JS_2_0
});
new Distribution(this, "distro", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = new S3Origin(s3Bucket),
FunctionAssociations = new [] { new FunctionAssociation {
Function = cfFunction,
EventType = FunctionEventType.VIEWER_REQUEST
} }
}
});
var s3Bucket Bucket
// Add a cloudfront Function to a Distribution
cfFunction := cloudfront.NewFunction(this, jsii.String("Function"), &FunctionProps{
Code: cloudfront.FunctionCode_FromInline(jsii.String("function handler(event) { return event.request }")),
Runtime: cloudfront.FunctionRuntime_JS_2_0(),
})
cloudfront.NewDistribution(this, jsii.String("distro"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewS3Origin(s3Bucket),
FunctionAssociations: []FunctionAssociation{
&FunctionAssociation{
Function: cfFunction,
EventType: cloudfront.FunctionEventType_VIEWER_REQUEST,
},
},
},
})
It will auto-generate the name of the function and deploy it to the live stage.
Additionally, you can load the function's code from a file using the FunctionCode.fromFile() method.
If you set autoPublish to false, the function will not be automatically published to the LIVE stage when it’s created.
new cloudfront.Function(this, 'Function', {
code: cloudfront.FunctionCode.fromInline('function handler(event) { return event.request }'),
runtime: cloudfront.FunctionRuntime.JS_2_0,
autoPublish: false
});
cloudfront.Function(self, "Function",
code=cloudfront.FunctionCode.from_inline("function handler(event) { return event.request }"),
runtime=cloudfront.FunctionRuntime.JS_2_0,
auto_publish=False
)
Function.Builder.create(this, "Function")
.code(FunctionCode.fromInline("function handler(event) { return event.request }"))
.runtime(FunctionRuntime.JS_2_0)
.autoPublish(false)
.build();
new Function(this, "Function", new FunctionProps {
Code = FunctionCode.FromInline("function handler(event) { return event.request }"),
Runtime = FunctionRuntime.JS_2_0,
AutoPublish = false
});
cloudfront.NewFunction(this, jsii.String("Function"), &FunctionProps{
Code: cloudfront.FunctionCode_FromInline(jsii.String("function handler(event) { return event.request }")),
Runtime: cloudfront.FunctionRuntime_JS_2_0(),
AutoPublish: jsii.Boolean(false),
})
Runtime Version
CloudFront Functions support two runtime versions: cloudfront-js-1.0 and cloudfront-js-2.0. By default, new projects use cloudfront-js-2.0, which is the recommended runtime version with enhanced functionality.
You can explicitly specify the runtime version:
// Use v2.0 explicitly (same as default for new projects)
new cloudfront.Function(this, 'Function', {
code: cloudfront.FunctionCode.fromInline('function handler(event) { return event.request }'),
runtime: cloudfront.FunctionRuntime.JS_2_0,
});
// Use v1.0 for legacy compatibility
new cloudfront.Function(this, 'Function', {
code: cloudfront.FunctionCode.fromInline('function handler(event) { return event.request }'),
runtime: cloudfront.FunctionRuntime.JS_1_0,
});
# Use v2.0 explicitly (same as default for new projects)
cloudfront.Function(self, "Function",
code=cloudfront.FunctionCode.from_inline("function handler(event) { return event.request }"),
runtime=cloudfront.FunctionRuntime.JS_2_0
)
# Use v1.0 for legacy compatibility
cloudfront.Function(self, "Function",
code=cloudfront.FunctionCode.from_inline("function handler(event) { return event.request }"),
runtime=cloudfront.FunctionRuntime.JS_1_0
)
// Use v2.0 explicitly (same as default for new projects)
// Use v2.0 explicitly (same as default for new projects)
Function.Builder.create(this, "Function")
.code(FunctionCode.fromInline("function handler(event) { return event.request }"))
.runtime(FunctionRuntime.JS_2_0)
.build();
// Use v1.0 for legacy compatibility
// Use v1.0 for legacy compatibility
Function.Builder.create(this, "Function")
.code(FunctionCode.fromInline("function handler(event) { return event.request }"))
.runtime(FunctionRuntime.JS_1_0)
.build();
// Use v2.0 explicitly (same as default for new projects)
// Use v2.0 explicitly (same as default for new projects)
new Function(this, "Function", new FunctionProps {
Code = FunctionCode.FromInline("function handler(event) { return event.request }"),
Runtime = FunctionRuntime.JS_2_0
});
// Use v1.0 for legacy compatibility
// Use v1.0 for legacy compatibility
new Function(this, "Function", new FunctionProps {
Code = FunctionCode.FromInline("function handler(event) { return event.request }"),
Runtime = FunctionRuntime.JS_1_0
});
// Use v2.0 explicitly (same as default for new projects)
// Use v2.0 explicitly (same as default for new projects)
cloudfront.NewFunction(this, jsii.String("Function"), &FunctionProps{
Code: cloudfront.FunctionCode_FromInline(jsii.String("function handler(event) { return event.request }")),
Runtime: cloudfront.FunctionRuntime_JS_2_0(),
})
// Use v1.0 for legacy compatibility
// Use v1.0 for legacy compatibility
cloudfront.NewFunction(this, jsii.String("Function"), &FunctionProps{
Code: cloudfront.FunctionCode_*FromInline(jsii.String("function handler(event) { return event.request }")),
Runtime: cloudfront.FunctionRuntime_JS_1_0(),
})
Note: Functions associated with a Key Value Store always use cloudfront-js-2.0, as Key Value Store support requires the v2.0 runtime.
When the @aws-cdk/aws-cloudfront:defaultFunctionRuntimeV2_0 feature flag is disabled, the runtime defaults to cloudfront-js-1.0 for backward compatibility.
Key Value Store
A CloudFront Key Value Store can be created and optionally have data imported from a JSON file by default.
To create an empty Key Value Store:
const store = new cloudfront.KeyValueStore(this, 'KeyValueStore');
store = cloudfront.KeyValueStore(self, "KeyValueStore")
KeyValueStore store = new KeyValueStore(this, "KeyValueStore");
var store = new KeyValueStore(this, "KeyValueStore");
store := cloudfront.NewKeyValueStore(this, jsii.String("KeyValueStore"))
To also include an initial set of values, the source property can be specified, either from a local file or an inline string. For the structure of this file, see Creating a file of key value pairs.
const storeAsset = new cloudfront.KeyValueStore(this, 'KeyValueStoreAsset', {
keyValueStoreName: 'KeyValueStoreAsset',
source: cloudfront.ImportSource.fromAsset('path-to-data.json'),
});
const storeInline = new cloudfront.KeyValueStore(this, 'KeyValueStoreInline', {
keyValueStoreName: 'KeyValueStoreInline',
source: cloudfront.ImportSource.fromInline(JSON.stringify({
data: [
{
key: "key1",
value: "value1",
},
{
key: "key2",
value: "value2",
},
],
})),
});
store_asset = cloudfront.KeyValueStore(self, "KeyValueStoreAsset",
key_value_store_name="KeyValueStoreAsset",
source=cloudfront.ImportSource.from_asset("path-to-data.json")
)
store_inline = cloudfront.KeyValueStore(self, "KeyValueStoreInline",
key_value_store_name="KeyValueStoreInline",
source=cloudfront.ImportSource.from_inline(JSON.stringify({
"data": [{
"key": "key1",
"value": "value1"
}, {
"key": "key2",
"value": "value2"
}
]
}))
)
KeyValueStore storeAsset = KeyValueStore.Builder.create(this, "KeyValueStoreAsset")
.keyValueStoreName("KeyValueStoreAsset")
.source(ImportSource.fromAsset("path-to-data.json"))
.build();
KeyValueStore storeInline = KeyValueStore.Builder.create(this, "KeyValueStoreInline")
.keyValueStoreName("KeyValueStoreInline")
.source(ImportSource.fromInline(JSON.stringify(Map.of(
"data", List.of(Map.of(
"key", "key1",
"value", "value1"), Map.of(
"key", "key2",
"value", "value2"))))))
.build();
var storeAsset = new KeyValueStore(this, "KeyValueStoreAsset", new KeyValueStoreProps {
KeyValueStoreName = "KeyValueStoreAsset",
Source = ImportSource.FromAsset("path-to-data.json")
});
var storeInline = new KeyValueStore(this, "KeyValueStoreInline", new KeyValueStoreProps {
KeyValueStoreName = "KeyValueStoreInline",
Source = ImportSource.FromInline(JSON.Stringify(new Dictionary<string, IDictionary<string, string>[]> {
{ "data", new [] { new Struct {
Key = "key1",
Value = "value1"
}, new Struct {
Key = "key2",
Value = "value2"
} } }
}))
});
storeAsset := cloudfront.NewKeyValueStore(this, jsii.String("KeyValueStoreAsset"), &KeyValueStoreProps{
KeyValueStoreName: jsii.String("KeyValueStoreAsset"),
Source: cloudfront.ImportSource_FromAsset(jsii.String("path-to-data.json")),
})
storeInline := cloudfront.NewKeyValueStore(this, jsii.String("KeyValueStoreInline"), &KeyValueStoreProps{
KeyValueStoreName: jsii.String("KeyValueStoreInline"),
Source: cloudfront.ImportSource_FromInline(jSON.stringify(map[string][]map[string]*string{
"data": []map[string]*string{
map[string]*string{
"key": jsii.String("key1"),
"value": jsii.String("value1"),
},
map[string]*string{
"key": jsii.String("key2"),
"value": jsii.String("value2"),
},
},
})),
})
The Key Value Store can then be associated to a function using the cloudfront-js-2.0 runtime or newer:
const store = new cloudfront.KeyValueStore(this, 'KeyValueStore');
new cloudfront.Function(this, 'Function', {
code: cloudfront.FunctionCode.fromInline('function handler(event) { return event.request }'),
// Note that JS_2_0 must be used for Key Value Store support
runtime: cloudfront.FunctionRuntime.JS_2_0,
keyValueStore: store,
});
store = cloudfront.KeyValueStore(self, "KeyValueStore")
cloudfront.Function(self, "Function",
code=cloudfront.FunctionCode.from_inline("function handler(event) { return event.request }"),
# Note that JS_2_0 must be used for Key Value Store support
runtime=cloudfront.FunctionRuntime.JS_2_0,
key_value_store=store
)
KeyValueStore store = new KeyValueStore(this, "KeyValueStore");
Function.Builder.create(this, "Function")
.code(FunctionCode.fromInline("function handler(event) { return event.request }"))
// Note that JS_2_0 must be used for Key Value Store support
.runtime(FunctionRuntime.JS_2_0)
.keyValueStore(store)
.build();
var store = new KeyValueStore(this, "KeyValueStore");
new Function(this, "Function", new FunctionProps {
Code = FunctionCode.FromInline("function handler(event) { return event.request }"),
// Note that JS_2_0 must be used for Key Value Store support
Runtime = FunctionRuntime.JS_2_0,
KeyValueStore = store
});
store := cloudfront.NewKeyValueStore(this, jsii.String("KeyValueStore"))
cloudfront.NewFunction(this, jsii.String("Function"), &FunctionProps{
Code: cloudfront.FunctionCode_FromInline(jsii.String("function handler(event) { return event.request }")),
// Note that JS_2_0 must be used for Key Value Store support
Runtime: cloudfront.FunctionRuntime_JS_2_0(),
KeyValueStore: store,
})
Logging
You can configure CloudFront to create log files that contain detailed information about every user request that CloudFront receives. The logs can go to either an existing bucket, or a bucket will be created for you.
// Configure logging for Distributions
// Simplest form - creates a new bucket and logs to it.
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.HttpOrigin('www.example.com') },
enableLogging: true,
});
// You can optionally log to a specific bucket, configure whether cookies are logged, and give the log files a prefix.
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.HttpOrigin('www.example.com') },
enableLogging: true, // Optional, this is implied if logBucket is specified
logBucket: new s3.Bucket(this, 'LogBucket', {
objectOwnership: s3.ObjectOwnership.OBJECT_WRITER,
}),
logFilePrefix: 'distribution-access-logs/',
logIncludesCookies: true,
});
# Configure logging for Distributions
# Simplest form - creates a new bucket and logs to it.
cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(origin=origins.HttpOrigin("www.example.com")),
enable_logging=True
)
# You can optionally log to a specific bucket, configure whether cookies are logged, and give the log files a prefix.
cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(origin=origins.HttpOrigin("www.example.com")),
enable_logging=True, # Optional, this is implied if logBucket is specified
log_bucket=s3.Bucket(self, "LogBucket",
object_ownership=s3.ObjectOwnership.OBJECT_WRITER
),
log_file_prefix="distribution-access-logs/",
log_includes_cookies=True
)
// Configure logging for Distributions
// Simplest form - creates a new bucket and logs to it.
// Configure logging for Distributions
// Simplest form - creates a new bucket and logs to it.
Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder().origin(new HttpOrigin("www.example.com")).build())
.enableLogging(true)
.build();
// You can optionally log to a specific bucket, configure whether cookies are logged, and give the log files a prefix.
// You can optionally log to a specific bucket, configure whether cookies are logged, and give the log files a prefix.
Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder().origin(new HttpOrigin("www.example.com")).build())
.enableLogging(true) // Optional, this is implied if logBucket is specified
.logBucket(Bucket.Builder.create(this, "LogBucket")
.objectOwnership(ObjectOwnership.OBJECT_WRITER)
.build())
.logFilePrefix("distribution-access-logs/")
.logIncludesCookies(true)
.build();
// Configure logging for Distributions
// Simplest form - creates a new bucket and logs to it.
// Configure logging for Distributions
// Simplest form - creates a new bucket and logs to it.
new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions { Origin = new HttpOrigin("www.example.com") },
EnableLogging = true
});
// You can optionally log to a specific bucket, configure whether cookies are logged, and give the log files a prefix.
// You can optionally log to a specific bucket, configure whether cookies are logged, and give the log files a prefix.
new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions { Origin = new HttpOrigin("www.example.com") },
EnableLogging = true, // Optional, this is implied if logBucket is specified
LogBucket = new Bucket(this, "LogBucket", new BucketProps {
ObjectOwnership = ObjectOwnership.OBJECT_WRITER
}),
LogFilePrefix = "distribution-access-logs/",
LogIncludesCookies = true
});
// Configure logging for Distributions
// Simplest form - creates a new bucket and logs to it.
// Configure logging for Distributions
// Simplest form - creates a new bucket and logs to it.
cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewHttpOrigin(jsii.String("www.example.com")),
},
EnableLogging: jsii.Boolean(true),
})
// You can optionally log to a specific bucket, configure whether cookies are logged, and give the log files a prefix.
// You can optionally log to a specific bucket, configure whether cookies are logged, and give the log files a prefix.
cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewHttpOrigin(jsii.String("www.example.com")),
},
EnableLogging: jsii.Boolean(true),
// Optional, this is implied if logBucket is specified
LogBucket: s3.NewBucket(this, jsii.String("LogBucket"), &BucketProps{
ObjectOwnership: s3.ObjectOwnership_OBJECT_WRITER,
}),
LogFilePrefix: jsii.String("distribution-access-logs/"),
LogIncludesCookies: jsii.Boolean(true),
})
CloudFront Distribution Metrics
You can view operational metrics about your CloudFront distributions.
Default CloudFront Distribution Metrics
The following metrics are available by default for all CloudFront distributions:
- Total requests: The total number of viewer requests received by CloudFront for all HTTP methods and for both HTTP and HTTPS requests.
- Total bytes uploaded: The total number of bytes that viewers uploaded to your origin with CloudFront, using POST and PUT requests.
- Total bytes downloaded: The total number of bytes downloaded by viewers for GET, HEAD, and OPTIONS requests.
- Total error rate: The percentage of all viewer requests for which the response's HTTP status code was 4xx or 5xx.
- 4xx error rate: The percentage of all viewer requests for which the response's HTTP status code was 4xx.
- 5xx error rate: The percentage of all viewer requests for which the response's HTTP status code was 5xx.
const dist = new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.HttpOrigin('www.example.com') },
});
// Retrieving default distribution metrics
const requestsMetric = dist.metricRequests();
const bytesUploadedMetric = dist.metricBytesUploaded();
const bytesDownloadedMetric = dist.metricBytesDownloaded();
const totalErrorRateMetric = dist.metricTotalErrorRate();
const http4xxErrorRateMetric = dist.metric4xxErrorRate();
const http5xxErrorRateMetric = dist.metric5xxErrorRate();
dist = cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(origin=origins.HttpOrigin("www.example.com"))
)
# Retrieving default distribution metrics
requests_metric = dist.metric_requests()
bytes_uploaded_metric = dist.metric_bytes_uploaded()
bytes_downloaded_metric = dist.metric_bytes_downloaded()
total_error_rate_metric = dist.metric_total_error_rate()
http4xx_error_rate_metric = dist.metric4xx_error_rate()
http5xx_error_rate_metric = dist.metric5xx_error_rate()
Distribution dist = Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder().origin(new HttpOrigin("www.example.com")).build())
.build();
// Retrieving default distribution metrics
Metric requestsMetric = dist.metricRequests();
Metric bytesUploadedMetric = dist.metricBytesUploaded();
Metric bytesDownloadedMetric = dist.metricBytesDownloaded();
Metric totalErrorRateMetric = dist.metricTotalErrorRate();
Metric http4xxErrorRateMetric = dist.metric4xxErrorRate();
Metric http5xxErrorRateMetric = dist.metric5xxErrorRate();
var dist = new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions { Origin = new HttpOrigin("www.example.com") }
});
// Retrieving default distribution metrics
var requestsMetric = dist.MetricRequests();
var bytesUploadedMetric = dist.MetricBytesUploaded();
var bytesDownloadedMetric = dist.MetricBytesDownloaded();
var totalErrorRateMetric = dist.MetricTotalErrorRate();
var http4xxErrorRateMetric = dist.Metric4xxErrorRate();
var http5xxErrorRateMetric = dist.Metric5xxErrorRate();
dist := cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewHttpOrigin(jsii.String("www.example.com")),
},
})
// Retrieving default distribution metrics
requestsMetric := dist.MetricRequests()
bytesUploadedMetric := dist.MetricBytesUploaded()
bytesDownloadedMetric := dist.MetricBytesDownloaded()
totalErrorRateMetric := dist.MetricTotalErrorRate()
http4xxErrorRateMetric := dist.Metric4xxErrorRate()
http5xxErrorRateMetric := dist.Metric5xxErrorRate()
Additional CloudFront Distribution Metrics
You can enable additional CloudFront distribution metrics, which include the following metrics:
- 4xx and 5xx error rates: View 4xx and 5xx error rates by the specific HTTP status code, as a percentage of total requests.
- Origin latency: See the total time spent from when CloudFront receives a request to when it provides a response to the network (not the viewer), for responses that are served from the origin, not the CloudFront cache.
- Cache hit rate: View cache hits as a percentage of total cacheable requests, excluding errors.
const dist = new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.HttpOrigin('www.example.com') },
publishAdditionalMetrics: true,
});
// Retrieving additional distribution metrics
const latencyMetric = dist.metricOriginLatency();
const cacheHitRateMetric = dist.metricCacheHitRate();
const http401ErrorRateMetric = dist.metric401ErrorRate();
const http403ErrorRateMetric = dist.metric403ErrorRate();
const http404ErrorRateMetric = dist.metric404ErrorRate();
const http502ErrorRateMetric = dist.metric502ErrorRate();
const http503ErrorRateMetric = dist.metric503ErrorRate();
const http504ErrorRateMetric = dist.metric504ErrorRate();
dist = cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(origin=origins.HttpOrigin("www.example.com")),
publish_additional_metrics=True
)
# Retrieving additional distribution metrics
latency_metric = dist.metric_origin_latency()
cache_hit_rate_metric = dist.metric_cache_hit_rate()
http401_error_rate_metric = dist.metric401_error_rate()
http403_error_rate_metric = dist.metric403_error_rate()
http404_error_rate_metric = dist.metric404_error_rate()
http502_error_rate_metric = dist.metric502_error_rate()
http503_error_rate_metric = dist.metric503_error_rate()
http504_error_rate_metric = dist.metric504_error_rate()
Distribution dist = Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder().origin(new HttpOrigin("www.example.com")).build())
.publishAdditionalMetrics(true)
.build();
// Retrieving additional distribution metrics
Metric latencyMetric = dist.metricOriginLatency();
Metric cacheHitRateMetric = dist.metricCacheHitRate();
Metric http401ErrorRateMetric = dist.metric401ErrorRate();
Metric http403ErrorRateMetric = dist.metric403ErrorRate();
Metric http404ErrorRateMetric = dist.metric404ErrorRate();
Metric http502ErrorRateMetric = dist.metric502ErrorRate();
Metric http503ErrorRateMetric = dist.metric503ErrorRate();
Metric http504ErrorRateMetric = dist.metric504ErrorRate();
var dist = new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions { Origin = new HttpOrigin("www.example.com") },
PublishAdditionalMetrics = true
});
// Retrieving additional distribution metrics
var latencyMetric = dist.MetricOriginLatency();
var cacheHitRateMetric = dist.MetricCacheHitRate();
var http401ErrorRateMetric = dist.Metric401ErrorRate();
var http403ErrorRateMetric = dist.Metric403ErrorRate();
var http404ErrorRateMetric = dist.Metric404ErrorRate();
var http502ErrorRateMetric = dist.Metric502ErrorRate();
var http503ErrorRateMetric = dist.Metric503ErrorRate();
var http504ErrorRateMetric = dist.Metric504ErrorRate();
dist := cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewHttpOrigin(jsii.String("www.example.com")),
},
PublishAdditionalMetrics: jsii.Boolean(true),
})
// Retrieving additional distribution metrics
latencyMetric := dist.MetricOriginLatency()
cacheHitRateMetric := dist.MetricCacheHitRate()
http401ErrorRateMetric := dist.Metric401ErrorRate()
http403ErrorRateMetric := dist.Metric403ErrorRate()
http404ErrorRateMetric := dist.Metric404ErrorRate()
http502ErrorRateMetric := dist.Metric502ErrorRate()
http503ErrorRateMetric := dist.Metric503ErrorRate()
http504ErrorRateMetric := dist.Metric504ErrorRate()
HTTP Versions
You can configure CloudFront to use a particular version of the HTTP protocol. By default, newly created distributions use HTTP/2 but can be configured to use both HTTP/2 and HTTP/3 or just HTTP/3. For all supported HTTP versions, see the HttpVerson enum.
// Configure a distribution to use HTTP/2 and HTTP/3
new cloudfront.Distribution(this, 'myDist', {
defaultBehavior: { origin: new origins.HttpOrigin('www.example.com') },
httpVersion: cloudfront.HttpVersion.HTTP2_AND_3,
});
# Configure a distribution to use HTTP/2 and HTTP/3
cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(origin=origins.HttpOrigin("www.example.com")),
http_version=cloudfront.HttpVersion.HTTP2_AND_3
)
// Configure a distribution to use HTTP/2 and HTTP/3
// Configure a distribution to use HTTP/2 and HTTP/3
Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder().origin(new HttpOrigin("www.example.com")).build())
.httpVersion(HttpVersion.HTTP2_AND_3)
.build();
// Configure a distribution to use HTTP/2 and HTTP/3
// Configure a distribution to use HTTP/2 and HTTP/3
new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions { Origin = new HttpOrigin("www.example.com") },
HttpVersion = HttpVersion.HTTP2_AND_3
});
// Configure a distribution to use HTTP/2 and HTTP/3
// Configure a distribution to use HTTP/2 and HTTP/3
cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewHttpOrigin(jsii.String("www.example.com")),
},
HttpVersion: cloudfront.HttpVersion_HTTP2_AND_3,
})
Importing Distributions
Existing distributions can be imported as well; note that like most imported constructs, an imported distribution cannot be modified. However, it can be used as a reference for other higher-level constructs.
// Using a reference to an imported Distribution
const distribution = cloudfront.Distribution.fromDistributionAttributes(this, 'ImportedDist', {
domainName: 'd111111abcdef8.cloudfront.net',
distributionId: '012345ABCDEF',
});
# Using a reference to an imported Distribution
distribution = cloudfront.Distribution.from_distribution_attributes(self, "ImportedDist",
domain_name="d111111abcdef8.cloudfront.net",
distribution_id="012345ABCDEF"
)
// Using a reference to an imported Distribution
IDistribution distribution = Distribution.fromDistributionAttributes(this, "ImportedDist", DistributionAttributes.builder()
.domainName("d111111abcdef8.cloudfront.net")
.distributionId("012345ABCDEF")
.build());
// Using a reference to an imported Distribution
var distribution = Distribution.FromDistributionAttributes(this, "ImportedDist", new DistributionAttributes {
DomainName = "d111111abcdef8.cloudfront.net",
DistributionId = "012345ABCDEF"
});
// Using a reference to an imported Distribution
distribution := cloudfront.Distribution_FromDistributionAttributes(this, jsii.String("ImportedDist"), &DistributionAttributes{
DomainName: jsii.String("d111111abcdef8.cloudfront.net"),
DistributionId: jsii.String("012345ABCDEF"),
})
Permissions
Use the grant() method to allow actions on the distribution. grantCreateInvalidation() is a shorthand to allow CreateInvalidation.
declare const distribution: cloudfront.Distribution;
declare const lambdaFn: lambda.Function;
distribution.grant(lambdaFn, 'cloudfront:ListInvalidations', 'cloudfront:GetInvalidation');
distribution.grantCreateInvalidation(lambdaFn);
# distribution: cloudfront.Distribution
# lambda_fn: lambda.Function
distribution.grant(lambda_fn, "cloudfront:ListInvalidations", "cloudfront:GetInvalidation")
distribution.grant_create_invalidation(lambda_fn)
Distribution distribution;
Function lambdaFn;
distribution.grant(lambdaFn, "cloudfront:ListInvalidations", "cloudfront:GetInvalidation");
distribution.grantCreateInvalidation(lambdaFn);
Distribution distribution;
Function lambdaFn;
distribution.Grant(lambdaFn, "cloudfront:ListInvalidations", "cloudfront:GetInvalidation");
distribution.GrantCreateInvalidation(lambdaFn);
var distribution Distribution
var lambdaFn Function
distribution.Grant(lambdaFn, jsii.String("cloudfront:ListInvalidations"), jsii.String("cloudfront:GetInvalidation"))
distribution.GrantCreateInvalidation(lambdaFn)
Realtime Log Config
CloudFront supports realtime log delivery from your distribution to a Kinesis stream.
See Real-time logs in the CloudFront User Guide.
Example:
// Adding realtime logs config to a Cloudfront Distribution on default behavior.
import * as kinesis from 'aws-cdk-lib/aws-kinesis';
declare const stream: kinesis.Stream;
const realTimeConfig = new cloudfront.RealtimeLogConfig(this, 'realtimeLog', {
endPoints: [
cloudfront.Endpoint.fromKinesisStream(stream),
],
fields: [
'timestamp',
'c-ip',
'time-to-first-byte',
'sc-status',
],
realtimeLogConfigName: 'my-delivery-stream',
samplingRate: 100,
});
new cloudfront.Distribution(this, 'myCdn', {
defaultBehavior: {
origin: new origins.HttpOrigin('www.example.com'),
realtimeLogConfig: realTimeConfig,
},
});
# Adding realtime logs config to a Cloudfront Distribution on default behavior.
import aws_cdk.aws_kinesis as kinesis
# stream: kinesis.Stream
real_time_config = cloudfront.RealtimeLogConfig(self, "realtimeLog",
end_points=[
cloudfront.Endpoint.from_kinesis_stream(stream)
],
fields=["timestamp", "c-ip", "time-to-first-byte", "sc-status"
],
realtime_log_config_name="my-delivery-stream",
sampling_rate=100
)
cloudfront.Distribution(self, "myCdn",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.HttpOrigin("www.example.com"),
realtime_log_config=real_time_config
)
)
// Adding realtime logs config to a Cloudfront Distribution on default behavior.
import software.amazon.awscdk.services.kinesis.*;
Stream stream;
RealtimeLogConfig realTimeConfig = RealtimeLogConfig.Builder.create(this, "realtimeLog")
.endPoints(List.of(Endpoint.fromKinesisStream(stream)))
.fields(List.of("timestamp", "c-ip", "time-to-first-byte", "sc-status"))
.realtimeLogConfigName("my-delivery-stream")
.samplingRate(100)
.build();
Distribution.Builder.create(this, "myCdn")
.defaultBehavior(BehaviorOptions.builder()
.origin(new HttpOrigin("www.example.com"))
.realtimeLogConfig(realTimeConfig)
.build())
.build();
// Adding realtime logs config to a Cloudfront Distribution on default behavior.
using Amazon.CDK.AWS.Kinesis;
Stream stream;
var realTimeConfig = new RealtimeLogConfig(this, "realtimeLog", new RealtimeLogConfigProps {
EndPoints = new [] { Endpoint.FromKinesisStream(stream) },
Fields = new [] { "timestamp", "c-ip", "time-to-first-byte", "sc-status" },
RealtimeLogConfigName = "my-delivery-stream",
SamplingRate = 100
});
new Distribution(this, "myCdn", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = new HttpOrigin("www.example.com"),
RealtimeLogConfig = realTimeConfig
}
});
// Adding realtime logs config to a Cloudfront Distribution on default behavior.
import kinesis "github.com/aws/aws-cdk-go/awscdk"
var stream Stream
realTimeConfig := cloudfront.NewRealtimeLogConfig(this, jsii.String("realtimeLog"), &RealtimeLogConfigProps{
EndPoints: []Endpoint{
cloudfront.Endpoint_FromKinesisStream(stream),
},
Fields: []*string{
jsii.String("timestamp"),
jsii.String("c-ip"),
jsii.String("time-to-first-byte"),
jsii.String("sc-status"),
},
RealtimeLogConfigName: jsii.String("my-delivery-stream"),
SamplingRate: jsii.Number(100),
})
cloudfront.NewDistribution(this, jsii.String("myCdn"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewHttpOrigin(jsii.String("www.example.com")),
RealtimeLogConfig: realTimeConfig,
},
})
gRPC
CloudFront supports gRPC, an open-source remote procedure call (RPC) framework built on HTTP/2. gRPC offers bi-directional streaming and binary protocol that buffers payloads, making it suitable for applications that require low latency communications.
To enable your distribution to handle gRPC requests, you must include HTTP/2 as one of the supported HTTP versions and allow HTTP methods, including POST.
See Using gRPC with CloudFront distributions in the CloudFront User Guide.
Example:
new cloudfront.Distribution(this, 'myCdn', {
defaultBehavior: {
origin: new origins.HttpOrigin('www.example.com'),
allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL, // `AllowedMethods.ALLOW_ALL` is required if `enableGrpc` is true
enableGrpc: true,
},
});
cloudfront.Distribution(self, "myCdn",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.HttpOrigin("www.example.com"),
allowed_methods=cloudfront.AllowedMethods.ALLOW_ALL, # `AllowedMethods.ALLOW_ALL` is required if `enableGrpc` is true
enable_grpc=True
)
)
Distribution.Builder.create(this, "myCdn")
.defaultBehavior(BehaviorOptions.builder()
.origin(new HttpOrigin("www.example.com"))
.allowedMethods(AllowedMethods.ALLOW_ALL) // `AllowedMethods.ALLOW_ALL` is required if `enableGrpc` is true
.enableGrpc(true)
.build())
.build();
new Distribution(this, "myCdn", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = new HttpOrigin("www.example.com"),
AllowedMethods = AllowedMethods.ALLOW_ALL, // `AllowedMethods.ALLOW_ALL` is required if `enableGrpc` is true
EnableGrpc = true
}
});
cloudfront.NewDistribution(this, jsii.String("myCdn"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewHttpOrigin(jsii.String("www.example.com")),
AllowedMethods: cloudfront.AllowedMethods_ALLOW_ALL(),
// `AllowedMethods.ALLOW_ALL` is required if `enableGrpc` is true
EnableGrpc: jsii.Boolean(true),
},
})
Migrating from the original CloudFrontWebDistribution to the newer Distribution construct
It's possible to migrate a distribution from the original to the modern API. The changes necessary are the following:
The Distribution
Replace new CloudFrontWebDistribution with new Distribution. Some configuration properties have been changed:
| Old API | New API |
|---|---|
originConfigs | defaultBehavior; use additionalBehaviors if necessary |
viewerCertificate | certificate; use domainNames for aliases |
errorConfigurations | errorResponses |
loggingConfig | enableLogging; configure with logBucket logFilePrefix and logIncludesCookies |
viewerProtocolPolicy | removed; set on each behavior instead. default changed from REDIRECT_TO_HTTPS to ALLOW_ALL, but the @aws-cdk/aws-cloudfront:defaultViewerProtocolPolicyRedirectToHttps feature flag restores REDIRECT_TO_HTTPS |
After switching constructs, you need to maintain the same logical ID for the underlying CfnDistribution if you wish to avoid the deletion and recreation of your distribution. To do this, use escape hatches to override the logical ID created by the new Distribution construct with the logical ID created by the old construct.
Example:
declare const sourceBucket: s3.Bucket;
const myDistribution = new cloudfront.Distribution(this, 'MyCfWebDistribution', {
defaultBehavior: {
origin: new origins.S3Origin(sourceBucket),
},
});
const cfnDistribution = myDistribution.node.defaultChild as cloudfront.CfnDistribution;
cfnDistribution.overrideLogicalId('MyDistributionCFDistribution3H55TI9Q');
# source_bucket: s3.Bucket
my_distribution = cloudfront.Distribution(self, "MyCfWebDistribution",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.S3Origin(source_bucket)
)
)
cfn_distribution = my_distribution.node.default_child
cfn_distribution.override_logical_id("MyDistributionCFDistribution3H55TI9Q")
Bucket sourceBucket;
Distribution myDistribution = Distribution.Builder.create(this, "MyCfWebDistribution")
.defaultBehavior(BehaviorOptions.builder()
.origin(new S3Origin(sourceBucket))
.build())
.build();
CfnDistribution cfnDistribution = (CfnDistribution)myDistribution.getNode().getDefaultChild();
cfnDistribution.overrideLogicalId("MyDistributionCFDistribution3H55TI9Q");
Bucket sourceBucket;
var myDistribution = new Distribution(this, "MyCfWebDistribution", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = new S3Origin(sourceBucket)
}
});
var cfnDistribution = (CfnDistribution)myDistribution.Node.DefaultChild;
cfnDistribution.OverrideLogicalId("MyDistributionCFDistribution3H55TI9Q");
var sourceBucket Bucket
myDistribution := cloudfront.NewDistribution(this, jsii.String("MyCfWebDistribution"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewS3Origin(sourceBucket),
},
})
cfnDistribution := myDistribution.Node.defaultChild.(CfnDistribution)
cfnDistribution.OverrideLogicalId(jsii.String("MyDistributionCFDistribution3H55TI9Q"))
Behaviors
The modern API makes use of the CloudFront Origins module to easily configure your origin. Replace your origin configuration with the relevant CloudFront Origins class. For example, here's a behavior with an S3 origin:
declare const sourceBucket: s3.Bucket;
declare const oai: cloudfront.OriginAccessIdentity;
new cloudfront.CloudFrontWebDistribution(this, 'MyCfWebDistribution', {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: sourceBucket,
originAccessIdentity: oai,
},
behaviors : [ {isDefaultBehavior: true}],
},
],
});
# source_bucket: s3.Bucket
# oai: cloudfront.OriginAccessIdentity
cloudfront.CloudFrontWebDistribution(self, "MyCfWebDistribution",
origin_configs=[cloudfront.SourceConfiguration(
s3_origin_source=cloudfront.S3OriginConfig(
s3_bucket_source=source_bucket,
origin_access_identity=oai
),
behaviors=[cloudfront.Behavior(is_default_behavior=True)]
)
]
)
Bucket sourceBucket;
OriginAccessIdentity oai;
CloudFrontWebDistribution.Builder.create(this, "MyCfWebDistribution")
.originConfigs(List.of(SourceConfiguration.builder()
.s3OriginSource(S3OriginConfig.builder()
.s3BucketSource(sourceBucket)
.originAccessIdentity(oai)
.build())
.behaviors(List.of(Behavior.builder().isDefaultBehavior(true).build()))
.build()))
.build();
Bucket sourceBucket;
OriginAccessIdentity oai;
new CloudFrontWebDistribution(this, "MyCfWebDistribution", new CloudFrontWebDistributionProps {
OriginConfigs = new [] { new SourceConfiguration {
S3OriginSource = new S3OriginConfig {
S3BucketSource = sourceBucket,
OriginAccessIdentity = oai
},
Behaviors = new [] { new Behavior { IsDefaultBehavior = true } }
} }
});
var sourceBucket Bucket
var oai OriginAccessIdentity
cloudfront.NewCloudFrontWebDistribution(this, jsii.String("MyCfWebDistribution"), &CloudFrontWebDistributionProps{
OriginConfigs: []SourceConfiguration{
&SourceConfiguration{
S3OriginSource: &S3OriginConfig{
S3BucketSource: sourceBucket,
OriginAccessIdentity: oai,
},
Behaviors: []Behavior{
&Behavior{
IsDefaultBehavior: jsii.Boolean(true),
},
},
},
},
})
Becomes:
declare const sourceBucket: s3.Bucket;
const distribution = new cloudfront.Distribution(this, 'MyCfWebDistribution', {
defaultBehavior: {
origin: new origins.S3Origin(sourceBucket) // This class automatically creates an Origin Access Identity
},
});
# source_bucket: s3.Bucket
distribution = cloudfront.Distribution(self, "MyCfWebDistribution",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.S3Origin(source_bucket)
)
)
Bucket sourceBucket;
Distribution distribution = Distribution.Builder.create(this, "MyCfWebDistribution")
.defaultBehavior(BehaviorOptions.builder()
.origin(new S3Origin(sourceBucket))
.build())
.build();
Bucket sourceBucket;
var distribution = new Distribution(this, "MyCfWebDistribution", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = new S3Origin(sourceBucket)
}
});
var sourceBucket Bucket
distribution := cloudfront.NewDistribution(this, jsii.String("MyCfWebDistribution"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewS3Origin(sourceBucket),
},
})
In the original API all behaviors are defined in the originConfigs property. The new API is optimized for a single origin and behavior, so the default behavior and additional behaviors will be defined separately.
declare const sourceBucket: s3.Bucket;
declare const oai: cloudfront.OriginAccessIdentity;
new cloudfront.CloudFrontWebDistribution(this, 'MyCfWebDistribution', {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: sourceBucket,
originAccessIdentity: oai,
},
behaviors: [ {isDefaultBehavior: true}],
},
{
customOriginSource: {
domainName: 'MYALIAS',
},
behaviors: [{ pathPattern: '/somewhere' }]
}
],
});
# source_bucket: s3.Bucket
# oai: cloudfront.OriginAccessIdentity
cloudfront.CloudFrontWebDistribution(self, "MyCfWebDistribution",
origin_configs=[cloudfront.SourceConfiguration(
s3_origin_source=cloudfront.S3OriginConfig(
s3_bucket_source=source_bucket,
origin_access_identity=oai
),
behaviors=[cloudfront.Behavior(is_default_behavior=True)]
), cloudfront.SourceConfiguration(
custom_origin_source=cloudfront.CustomOriginConfig(
domain_name="MYALIAS"
),
behaviors=[cloudfront.Behavior(path_pattern="/somewhere")]
)
]
)
Bucket sourceBucket;
OriginAccessIdentity oai;
CloudFrontWebDistribution.Builder.create(this, "MyCfWebDistribution")
.originConfigs(List.of(SourceConfiguration.builder()
.s3OriginSource(S3OriginConfig.builder()
.s3BucketSource(sourceBucket)
.originAccessIdentity(oai)
.build())
.behaviors(List.of(Behavior.builder().isDefaultBehavior(true).build()))
.build(), SourceConfiguration.builder()
.customOriginSource(CustomOriginConfig.builder()
.domainName("MYALIAS")
.build())
.behaviors(List.of(Behavior.builder().pathPattern("/somewhere").build()))
.build()))
.build();
Bucket sourceBucket;
OriginAccessIdentity oai;
new CloudFrontWebDistribution(this, "MyCfWebDistribution", new CloudFrontWebDistributionProps {
OriginConfigs = new [] { new SourceConfiguration {
S3OriginSource = new S3OriginConfig {
S3BucketSource = sourceBucket,
OriginAccessIdentity = oai
},
Behaviors = new [] { new Behavior { IsDefaultBehavior = true } }
}, new SourceConfiguration {
CustomOriginSource = new CustomOriginConfig {
DomainName = "MYALIAS"
},
Behaviors = new [] { new Behavior { PathPattern = "/somewhere" } }
} }
});
var sourceBucket Bucket
var oai OriginAccessIdentity
cloudfront.NewCloudFrontWebDistribution(this, jsii.String("MyCfWebDistribution"), &CloudFrontWebDistributionProps{
OriginConfigs: []SourceConfiguration{
&SourceConfiguration{
S3OriginSource: &S3OriginConfig{
S3BucketSource: sourceBucket,
OriginAccessIdentity: oai,
},
Behaviors: []Behavior{
&Behavior{
IsDefaultBehavior: jsii.Boolean(true),
},
},
},
&SourceConfiguration{
CustomOriginSource: &CustomOriginConfig{
DomainName: jsii.String("MYALIAS"),
},
Behaviors: []Behavior{
&Behavior{
PathPattern: jsii.String("/somewhere"),
},
},
},
},
})
Becomes:
declare const sourceBucket: s3.Bucket;
const distribution = new cloudfront.Distribution(this, 'MyCfWebDistribution', {
defaultBehavior: {
origin: new origins.S3Origin(sourceBucket) // This class automatically creates an Origin Access Identity
},
additionalBehaviors: {
'/somewhere': {
origin: new origins.HttpOrigin('MYALIAS'),
}
}
});
# source_bucket: s3.Bucket
distribution = cloudfront.Distribution(self, "MyCfWebDistribution",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.S3Origin(source_bucket)
),
additional_behaviors={
"/somewhere": cloudfront.BehaviorOptions(
origin=origins.HttpOrigin("MYALIAS")
)
}
)
Bucket sourceBucket;
Distribution distribution = Distribution.Builder.create(this, "MyCfWebDistribution")
.defaultBehavior(BehaviorOptions.builder()
.origin(new S3Origin(sourceBucket))
.build())
.additionalBehaviors(Map.of(
"/somewhere", BehaviorOptions.builder()
.origin(new HttpOrigin("MYALIAS"))
.build()))
.build();
Bucket sourceBucket;
var distribution = new Distribution(this, "MyCfWebDistribution", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = new S3Origin(sourceBucket)
},
AdditionalBehaviors = new Dictionary<string, BehaviorOptions> {
{ "/somewhere", new BehaviorOptions {
Origin = new HttpOrigin("MYALIAS")
} }
}
});
var sourceBucket Bucket
distribution := cloudfront.NewDistribution(this, jsii.String("MyCfWebDistribution"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewS3Origin(sourceBucket),
},
AdditionalBehaviors: map[string]BehaviorOptions{
"/somewhere": &BehaviorOptions{
"origin": origins.NewHttpOrigin(jsii.String("MYALIAS")),
},
},
})
Certificates
If you are using an ACM certificate, you can pass the certificate directly to the certificate prop. Any aliases used before in the ViewerCertificate class should be passed in to the domainNames prop in the modern API.
import * as acm from 'aws-cdk-lib/aws-certificatemanager';
declare const certificate: acm.Certificate;
declare const sourceBucket: s3.Bucket;
const viewerCertificate = cloudfront.ViewerCertificate.fromAcmCertificate(certificate, {
aliases: ['MYALIAS'],
});
new cloudfront.CloudFrontWebDistribution(this, 'MyCfWebDistribution', {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: sourceBucket,
},
behaviors : [ {isDefaultBehavior: true} ],
},
],
viewerCertificate: viewerCertificate,
});
import aws_cdk.aws_certificatemanager as acm
# certificate: acm.Certificate
# source_bucket: s3.Bucket
viewer_certificate = cloudfront.ViewerCertificate.from_acm_certificate(certificate,
aliases=["MYALIAS"]
)
cloudfront.CloudFrontWebDistribution(self, "MyCfWebDistribution",
origin_configs=[cloudfront.SourceConfiguration(
s3_origin_source=cloudfront.S3OriginConfig(
s3_bucket_source=source_bucket
),
behaviors=[cloudfront.Behavior(is_default_behavior=True)]
)
],
viewer_certificate=viewer_certificate
)
import software.amazon.awscdk.services.certificatemanager.*;
Certificate certificate;
Bucket sourceBucket;
ViewerCertificate viewerCertificate = ViewerCertificate.fromAcmCertificate(certificate, ViewerCertificateOptions.builder()
.aliases(List.of("MYALIAS"))
.build());
CloudFrontWebDistribution.Builder.create(this, "MyCfWebDistribution")
.originConfigs(List.of(SourceConfiguration.builder()
.s3OriginSource(S3OriginConfig.builder()
.s3BucketSource(sourceBucket)
.build())
.behaviors(List.of(Behavior.builder().isDefaultBehavior(true).build()))
.build()))
.viewerCertificate(viewerCertificate)
.build();
using Amazon.CDK.AWS.CertificateManager;
Certificate certificate;
Bucket sourceBucket;
var viewerCertificate = ViewerCertificate.FromAcmCertificate(certificate, new ViewerCertificateOptions {
Aliases = new [] { "MYALIAS" }
});
new CloudFrontWebDistribution(this, "MyCfWebDistribution", new CloudFrontWebDistributionProps {
OriginConfigs = new [] { new SourceConfiguration {
S3OriginSource = new S3OriginConfig {
S3BucketSource = sourceBucket
},
Behaviors = new [] { new Behavior { IsDefaultBehavior = true } }
} },
ViewerCertificate = viewerCertificate
});
import acm "github.com/aws/aws-cdk-go/awscdk"
var certificate Certificate
var sourceBucket Bucket
viewerCertificate := cloudfront.ViewerCertificate_FromAcmCertificate(certificate, &ViewerCertificateOptions{
Aliases: []*string{
jsii.String("MYALIAS"),
},
})
cloudfront.NewCloudFrontWebDistribution(this, jsii.String("MyCfWebDistribution"), &CloudFrontWebDistributionProps{
OriginConfigs: []SourceConfiguration{
&SourceConfiguration{
S3OriginSource: &S3OriginConfig{
S3BucketSource: sourceBucket,
},
Behaviors: []Behavior{
&Behavior{
IsDefaultBehavior: jsii.Boolean(true),
},
},
},
},
ViewerCertificate: viewerCertificate,
})
Becomes:
import * as acm from 'aws-cdk-lib/aws-certificatemanager';
declare const certificate: acm.Certificate;
declare const sourceBucket: s3.Bucket;
const distribution = new cloudfront.Distribution(this, 'MyCfWebDistribution', {
defaultBehavior: {
origin: new origins.S3Origin(sourceBucket),
},
domainNames: ['MYALIAS'],
certificate: certificate,
});
import aws_cdk.aws_certificatemanager as acm
# certificate: acm.Certificate
# source_bucket: s3.Bucket
distribution = cloudfront.Distribution(self, "MyCfWebDistribution",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.S3Origin(source_bucket)
),
domain_names=["MYALIAS"],
certificate=certificate
)
import software.amazon.awscdk.services.certificatemanager.*;
Certificate certificate;
Bucket sourceBucket;
Distribution distribution = Distribution.Builder.create(this, "MyCfWebDistribution")
.defaultBehavior(BehaviorOptions.builder()
.origin(new S3Origin(sourceBucket))
.build())
.domainNames(List.of("MYALIAS"))
.certificate(certificate)
.build();
using Amazon.CDK.AWS.CertificateManager;
Certificate certificate;
Bucket sourceBucket;
var distribution = new Distribution(this, "MyCfWebDistribution", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = new S3Origin(sourceBucket)
},
DomainNames = new [] { "MYALIAS" },
Certificate = certificate
});
import acm "github.com/aws/aws-cdk-go/awscdk"
var certificate Certificate
var sourceBucket Bucket
distribution := cloudfront.NewDistribution(this, jsii.String("MyCfWebDistribution"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewS3Origin(sourceBucket),
},
DomainNames: []*string{
jsii.String("MYALIAS"),
},
Certificate: certificate,
})
IAM certificates aren't directly supported by the new API, but can be easily configured through escape hatches
declare const sourceBucket: s3.Bucket;
const viewerCertificate = cloudfront.ViewerCertificate.fromIamCertificate('MYIAMROLEIDENTIFIER', {
aliases: ['MYALIAS'],
});
new cloudfront.CloudFrontWebDistribution(this, 'MyCfWebDistribution', {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: sourceBucket,
},
behaviors : [ {isDefaultBehavior: true} ],
},
],
viewerCertificate: viewerCertificate,
});
# source_bucket: s3.Bucket
viewer_certificate = cloudfront.ViewerCertificate.from_iam_certificate("MYIAMROLEIDENTIFIER",
aliases=["MYALIAS"]
)
cloudfront.CloudFrontWebDistribution(self, "MyCfWebDistribution",
origin_configs=[cloudfront.SourceConfiguration(
s3_origin_source=cloudfront.S3OriginConfig(
s3_bucket_source=source_bucket
),
behaviors=[cloudfront.Behavior(is_default_behavior=True)]
)
],
viewer_certificate=viewer_certificate
)
Bucket sourceBucket;
ViewerCertificate viewerCertificate = ViewerCertificate.fromIamCertificate("MYIAMROLEIDENTIFIER", ViewerCertificateOptions.builder()
.aliases(List.of("MYALIAS"))
.build());
CloudFrontWebDistribution.Builder.create(this, "MyCfWebDistribution")
.originConfigs(List.of(SourceConfiguration.builder()
.s3OriginSource(S3OriginConfig.builder()
.s3BucketSource(sourceBucket)
.build())
.behaviors(List.of(Behavior.builder().isDefaultBehavior(true).build()))
.build()))
.viewerCertificate(viewerCertificate)
.build();
Bucket sourceBucket;
var viewerCertificate = ViewerCertificate.FromIamCertificate("MYIAMROLEIDENTIFIER", new ViewerCertificateOptions {
Aliases = new [] { "MYALIAS" }
});
new CloudFrontWebDistribution(this, "MyCfWebDistribution", new CloudFrontWebDistributionProps {
OriginConfigs = new [] { new SourceConfiguration {
S3OriginSource = new S3OriginConfig {
S3BucketSource = sourceBucket
},
Behaviors = new [] { new Behavior { IsDefaultBehavior = true } }
} },
ViewerCertificate = viewerCertificate
});
var sourceBucket Bucket
viewerCertificate := cloudfront.ViewerCertificate_FromIamCertificate(jsii.String("MYIAMROLEIDENTIFIER"), &ViewerCertificateOptions{
Aliases: []*string{
jsii.String("MYALIAS"),
},
})
cloudfront.NewCloudFrontWebDistribution(this, jsii.String("MyCfWebDistribution"), &CloudFrontWebDistributionProps{
OriginConfigs: []SourceConfiguration{
&SourceConfiguration{
S3OriginSource: &S3OriginConfig{
S3BucketSource: sourceBucket,
},
Behaviors: []Behavior{
&Behavior{
IsDefaultBehavior: jsii.Boolean(true),
},
},
},
},
ViewerCertificate: viewerCertificate,
})
Becomes:
declare const sourceBucket: s3.Bucket;
const distribution = new cloudfront.Distribution(this, 'MyCfWebDistribution', {
defaultBehavior: {
origin: new origins.S3Origin(sourceBucket),
},
domainNames: ['MYALIAS'],
});
const cfnDistribution = distribution.node.defaultChild as cloudfront.CfnDistribution;
cfnDistribution.addPropertyOverride('ViewerCertificate.IamCertificateId', 'MYIAMROLEIDENTIFIER');
cfnDistribution.addPropertyOverride('ViewerCertificate.SslSupportMethod', 'sni-only');
# source_bucket: s3.Bucket
distribution = cloudfront.Distribution(self, "MyCfWebDistribution",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.S3Origin(source_bucket)
),
domain_names=["MYALIAS"]
)
cfn_distribution = distribution.node.default_child
cfn_distribution.add_property_override("ViewerCertificate.IamCertificateId", "MYIAMROLEIDENTIFIER")
cfn_distribution.add_property_override("ViewerCertificate.SslSupportMethod", "sni-only")
Bucket sourceBucket;
Distribution distribution = Distribution.Builder.create(this, "MyCfWebDistribution")
.defaultBehavior(BehaviorOptions.builder()
.origin(new S3Origin(sourceBucket))
.build())
.domainNames(List.of("MYALIAS"))
.build();
CfnDistribution cfnDistribution = (CfnDistribution)distribution.getNode().getDefaultChild();
cfnDistribution.addPropertyOverride("ViewerCertificate.IamCertificateId", "MYIAMROLEIDENTIFIER");
cfnDistribution.addPropertyOverride("ViewerCertificate.SslSupportMethod", "sni-only");
Bucket sourceBucket;
var distribution = new Distribution(this, "MyCfWebDistribution", new DistributionProps {
DefaultBehavior = new BehaviorOptions {
Origin = new S3Origin(sourceBucket)
},
DomainNames = new [] { "MYALIAS" }
});
var cfnDistribution = (CfnDistribution)distribution.Node.DefaultChild;
cfnDistribution.AddPropertyOverride("ViewerCertificate.IamCertificateId", "MYIAMROLEIDENTIFIER");
cfnDistribution.AddPropertyOverride("ViewerCertificate.SslSupportMethod", "sni-only");
var sourceBucket Bucket
distribution := cloudfront.NewDistribution(this, jsii.String("MyCfWebDistribution"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.NewS3Origin(sourceBucket),
},
DomainNames: []*string{
jsii.String("MYALIAS"),
},
})
cfnDistribution := distribution.Node.defaultChild.(CfnDistribution)
cfnDistribution.AddPropertyOverride(jsii.String("ViewerCertificate.IamCertificateId"), jsii.String("MYIAMROLEIDENTIFIER"))
cfnDistribution.AddPropertyOverride(jsii.String("ViewerCertificate.SslSupportMethod"), jsii.String("sni-only"))
Other changes
A number of default settings have changed on the new API when creating a new distribution, behavior, and origin. After making the major changes needed for the migration, run cdk diff to see what settings have changed. If no changes are desired during migration, you will at the least be able to use escape hatches to override what the CDK synthesizes, if you can't change the properties directly.
CloudFrontWebDistribution API
The
CloudFrontWebDistributionconstruct is the original construct written for working with CloudFront distributions and has been marked as deprecated. Users are encouraged to use the newerDistributioninstead, as it has a simpler interface and receives new features faster.
Example usage:
// Using a CloudFrontWebDistribution construct.
declare const sourceBucket: s3.Bucket;
const distribution = new cloudfront.CloudFrontWebDistribution(this, 'MyDistribution', {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: sourceBucket,
},
behaviors : [ {isDefaultBehavior: true}],
},
],
});
# Using a CloudFrontWebDistribution construct.
# source_bucket: s3.Bucket
distribution = cloudfront.CloudFrontWebDistribution(self, "MyDistribution",
origin_configs=[cloudfront.SourceConfiguration(
s3_origin_source=cloudfront.S3OriginConfig(
s3_bucket_source=source_bucket
),
behaviors=[cloudfront.Behavior(is_default_behavior=True)]
)
]
)
// Using a CloudFrontWebDistribution construct.
Bucket sourceBucket;
CloudFrontWebDistribution distribution = CloudFrontWebDistribution.Builder.create(this, "MyDistribution")
.originConfigs(List.of(SourceConfiguration.builder()
.s3OriginSource(S3OriginConfig.builder()
.s3BucketSource(sourceBucket)
.build())
.behaviors(List.of(Behavior.builder().isDefaultBehavior(true).build()))
.build()))
.build();
// Using a CloudFrontWebDistribution construct.
Bucket sourceBucket;
var distribution = new CloudFrontWebDistribution(this, "MyDistribution", new CloudFrontWebDistributionProps {
OriginConfigs = new [] { new SourceConfiguration {
S3OriginSource = new S3OriginConfig {
S3BucketSource = sourceBucket
},
Behaviors = new [] { new Behavior { IsDefaultBehavior = true } }
} }
});
// Using a CloudFrontWebDistribution construct.
var sourceBucket Bucket
distribution := cloudfront.NewCloudFrontWebDistribution(this, jsii.String("MyDistribution"), &CloudFrontWebDistributionProps{
OriginConfigs: []SourceConfiguration{
&SourceConfiguration{
S3OriginSource: &S3OriginConfig{
S3BucketSource: sourceBucket,
},
Behaviors: []Behavior{
&Behavior{
IsDefaultBehavior: jsii.Boolean(true),
},
},
},
},
})
Viewer certificate
By default, CloudFront Web Distributions will answer HTTPS requests with CloudFront's default certificate, only containing the distribution domainName (e.g. d111111abcdef8.cloudfront.net). You can customize the viewer certificate property to provide a custom certificate and/or list of domain name aliases to fit your needs.
See Using Alternate Domain Names and HTTPS in the CloudFront User Guide.
Default certificate
You can customize the default certificate aliases. This is intended to be used in combination with CNAME records in your DNS zone.
Example:
const s3BucketSource = new s3.Bucket(this, 'Bucket');
const distribution = new cloudfront.CloudFrontWebDistribution(this, 'AnAmazingWebsiteProbably', {
originConfigs: [{
s3OriginSource: { s3BucketSource },
behaviors: [{ isDefaultBehavior: true }],
}],
viewerCertificate: cloudfront.ViewerCertificate.fromCloudFrontDefaultCertificate(
'www.example.com',
),
});
s3_bucket_source = s3.Bucket(self, "Bucket")
distribution = cloudfront.CloudFrontWebDistribution(self, "AnAmazingWebsiteProbably",
origin_configs=[cloudfront.aws_cloudfront.SourceConfiguration(
s3_origin_source=cloudfront.aws_cloudfront.S3OriginConfig(s3_bucket_source=s3_bucket_source),
behaviors=[cloudfront.aws_cloudfront.Behavior(is_default_behavior=True)]
)],
viewer_certificate=cloudfront.ViewerCertificate.from_cloud_front_default_certificate("www.example.com")
)
Bucket s3BucketSource = new Bucket(this, "Bucket");
CloudFrontWebDistribution distribution = CloudFrontWebDistribution.Builder.create(this, "AnAmazingWebsiteProbably")
.originConfigs(List.of(SourceConfiguration.builder()
.s3OriginSource(S3OriginConfig.builder().s3BucketSource(s3BucketSource).build())
.behaviors(List.of(Behavior.builder().isDefaultBehavior(true).build()))
.build()))
.viewerCertificate(ViewerCertificate.fromCloudFrontDefaultCertificate("www.example.com"))
.build();
var s3BucketSource = new Bucket(this, "Bucket");
var distribution = new CloudFrontWebDistribution(this, "AnAmazingWebsiteProbably", new CloudFrontWebDistributionProps {
OriginConfigs = new [] { new SourceConfiguration {
S3OriginSource = new S3OriginConfig { S3BucketSource = s3BucketSource },
Behaviors = new [] { new Behavior { IsDefaultBehavior = true } }
} },
ViewerCertificate = ViewerCertificate.FromCloudFrontDefaultCertificate("www.example.com")
});
s3BucketSource := s3.NewBucket(this, jsii.String("Bucket"))
distribution := cloudfront.NewCloudFrontWebDistribution(this, jsii.String("AnAmazingWebsiteProbably"), &CloudFrontWebDistributionProps{
OriginConfigs: []SourceConfiguration{
&SourceConfiguration{
S3OriginSource: &S3OriginConfig{
S3BucketSource: *S3BucketSource,
},
Behaviors: []Behavior{
&Behavior{
IsDefaultBehavior: jsii.Boolean(true),
},
},
},
},
ViewerCertificate: cloudfront.ViewerCertificate_FromCloudFrontDefaultCertificate(jsii.String("www.example.com")),
})
ACM certificate
You can change the default certificate by one stored AWS Certificate Manager, or ACM. Those certificate can either be generated by AWS, or purchased by another CA imported into ACM.
For more information, see the aws-certificatemanager module documentation or Importing Certificates into AWS Certificate Manager in the AWS Certificate Manager User Guide.
Example:
const s3BucketSource = new s3.Bucket(this, 'Bucket');
const certificate = new certificatemanager.Certificate(this, 'Certificate', {
domainName: 'example.com',
subjectAlternativeNames: ['*.example.com'],
});
const distribution = new cloudfront.CloudFrontWebDistribution(this, 'AnAmazingWebsiteProbably', {
originConfigs: [{
s3OriginSource: { s3BucketSource },
behaviors: [{ isDefaultBehavior: true }],
}],
viewerCertificate: cloudfront.ViewerCertificate.fromAcmCertificate(
certificate,
{
aliases: ['example.com', 'www.example.com'],
securityPolicy: cloudfront.SecurityPolicyProtocol.TLS_V1, // default
sslMethod: cloudfront.SSLMethod.SNI, // default
},
),
});
s3_bucket_source = s3.Bucket(self, "Bucket")
certificate = certificatemanager.Certificate(self, "Certificate",
domain_name="example.com",
subject_alternative_names=["*.example.com"]
)
distribution = cloudfront.CloudFrontWebDistribution(self, "AnAmazingWebsiteProbably",
origin_configs=[cloudfront.aws_cloudfront.SourceConfiguration(
s3_origin_source=cloudfront.aws_cloudfront.S3OriginConfig(s3_bucket_source=s3_bucket_source),
behaviors=[cloudfront.aws_cloudfront.Behavior(is_default_behavior=True)]
)],
viewer_certificate=cloudfront.ViewerCertificate.from_acm_certificate(certificate,
aliases=["example.com", "www.example.com"],
security_policy=cloudfront.SecurityPolicyProtocol.TLS_V1, # default
ssl_method=cloudfront.SSLMethod.SNI
)
)
Bucket s3BucketSource = new Bucket(this, "Bucket");
Certificate certificate = Certificate.Builder.create(this, "Certificate")
.domainName("example.com")
.subjectAlternativeNames(List.of("*.example.com"))
.build();
CloudFrontWebDistribution distribution = CloudFrontWebDistribution.Builder.create(this, "AnAmazingWebsiteProbably")
.originConfigs(List.of(SourceConfiguration.builder()
.s3OriginSource(S3OriginConfig.builder().s3BucketSource(s3BucketSource).build())
.behaviors(List.of(Behavior.builder().isDefaultBehavior(true).build()))
.build()))
.viewerCertificate(ViewerCertificate.fromAcmCertificate(certificate, ViewerCertificateOptions.builder()
.aliases(List.of("example.com", "www.example.com"))
.securityPolicy(SecurityPolicyProtocol.TLS_V1) // default
.sslMethod(SSLMethod.SNI)
.build()))
.build();
var s3BucketSource = new Bucket(this, "Bucket");
var certificate = new Certificate(this, "Certificate", new CertificateProps {
DomainName = "example.com",
SubjectAlternativeNames = new [] { "*.example.com" }
});
var distribution = new CloudFrontWebDistribution(this, "AnAmazingWebsiteProbably", new CloudFrontWebDistributionProps {
OriginConfigs = new [] { new SourceConfiguration {
S3OriginSource = new S3OriginConfig { S3BucketSource = s3BucketSource },
Behaviors = new [] { new Behavior { IsDefaultBehavior = true } }
} },
ViewerCertificate = ViewerCertificate.FromAcmCertificate(certificate, new ViewerCertificateOptions {
Aliases = new [] { "example.com", "www.example.com" },
SecurityPolicy = SecurityPolicyProtocol.TLS_V1, // default
SslMethod = SSLMethod.SNI
})
});
s3BucketSource := s3.NewBucket(this, jsii.String("Bucket"))
certificate := certificatemanager.NewCertificate(this, jsii.String("Certificate"), &CertificateProps{
DomainName: jsii.String("example.com"),
SubjectAlternativeNames: []*string{
jsii.String("*.example.com"),
},
})
distribution := cloudfront.NewCloudFrontWebDistribution(this, jsii.String("AnAmazingWebsiteProbably"), &CloudFrontWebDistributionProps{
OriginConfigs: []SourceConfiguration{
&SourceConfiguration{
S3OriginSource: &S3OriginConfig{
S3BucketSource: *S3BucketSource,
},
Behaviors: []Behavior{
&Behavior{
IsDefaultBehavior: jsii.Boolean(true),
},
},
},
},
ViewerCertificate: cloudfront.ViewerCertificate_FromAcmCertificate(certificate, &ViewerCertificateOptions{
Aliases: []*string{
jsii.String("example.com"),
jsii.String("www.example.com"),
},
SecurityPolicy: cloudfront.SecurityPolicyProtocol_TLS_V1,
// default
SslMethod: cloudfront.SSLMethod_SNI,
}),
})
IAM certificate
You can also import a certificate into the IAM certificate store.
See Importing an SSL/TLS Certificate in the CloudFront User Guide.
Example:
const s3BucketSource = new s3.Bucket(this, 'Bucket');
const distribution = new cloudfront.CloudFrontWebDistribution(this, 'AnAmazingWebsiteProbably', {
originConfigs: [{
s3OriginSource: { s3BucketSource },
behaviors: [{ isDefaultBehavior: true }],
}],
viewerCertificate: cloudfront.ViewerCertificate.fromIamCertificate(
'certificateId',
{
aliases: ['example.com'],
securityPolicy: cloudfront.SecurityPolicyProtocol.SSL_V3, // default
sslMethod: cloudfront.SSLMethod.SNI, // default
},
),
});
s3_bucket_source = s3.Bucket(self, "Bucket")
distribution = cloudfront.CloudFrontWebDistribution(self, "AnAmazingWebsiteProbably",
origin_configs=[cloudfront.aws_cloudfront.SourceConfiguration(
s3_origin_source=cloudfront.aws_cloudfront.S3OriginConfig(s3_bucket_source=s3_bucket_source),
behaviors=[cloudfront.aws_cloudfront.Behavior(is_default_behavior=True)]
)],
viewer_certificate=cloudfront.ViewerCertificate.from_iam_certificate("certificateId",
aliases=["example.com"],
security_policy=cloudfront.SecurityPolicyProtocol.SSL_V3, # default
ssl_method=cloudfront.SSLMethod.SNI
)
)
Bucket s3BucketSource = new Bucket(this, "Bucket");
CloudFrontWebDistribution distribution = CloudFrontWebDistribution.Builder.create(this, "AnAmazingWebsiteProbably")
.originConfigs(List.of(SourceConfiguration.builder()
.s3OriginSource(S3OriginConfig.builder().s3BucketSource(s3BucketSource).build())
.behaviors(List.of(Behavior.builder().isDefaultBehavior(true).build()))
.build()))
.viewerCertificate(ViewerCertificate.fromIamCertificate("certificateId", ViewerCertificateOptions.builder()
.aliases(List.of("example.com"))
.securityPolicy(SecurityPolicyProtocol.SSL_V3) // default
.sslMethod(SSLMethod.SNI)
.build()))
.build();
var s3BucketSource = new Bucket(this, "Bucket");
var distribution = new CloudFrontWebDistribution(this, "AnAmazingWebsiteProbably", new CloudFrontWebDistributionProps {
OriginConfigs = new [] { new SourceConfiguration {
S3OriginSource = new S3OriginConfig { S3BucketSource = s3BucketSource },
Behaviors = new [] { new Behavior { IsDefaultBehavior = true } }
} },
ViewerCertificate = ViewerCertificate.FromIamCertificate("certificateId", new ViewerCertificateOptions {
Aliases = new [] { "example.com" },
SecurityPolicy = SecurityPolicyProtocol.SSL_V3, // default
SslMethod = SSLMethod.SNI
})
});
s3BucketSource := s3.NewBucket(this, jsii.String("Bucket"))
distribution := cloudfront.NewCloudFrontWebDistribution(this, jsii.String("AnAmazingWebsiteProbably"), &CloudFrontWebDistributionProps{
OriginConfigs: []SourceConfiguration{
&SourceConfiguration{
S3OriginSource: &S3OriginConfig{
S3BucketSource: *S3BucketSource,
},
Behaviors: []Behavior{
&Behavior{
IsDefaultBehavior: jsii.Boolean(true),
},
},
},
},
ViewerCertificate: cloudfront.ViewerCertificate_FromIamCertificate(jsii.String("certificateId"), &ViewerCertificateOptions{
Aliases: []*string{
jsii.String("example.com"),
},
SecurityPolicy: cloudfront.SecurityPolicyProtocol_SSL_V3,
// default
SslMethod: cloudfront.SSLMethod_SNI,
}),
})
Trusted Key Groups
CloudFront Web Distributions supports validating signed URLs or signed cookies using key groups. When a cache behavior contains trusted key groups, CloudFront requires signed URLs or signed cookies for all requests that match the cache behavior.
Example:
// Using trusted key groups for Cloudfront Web Distributions.
declare const sourceBucket: s3.Bucket;
declare const publicKey: string;
const pubKey = new cloudfront.PublicKey(this, 'MyPubKey', {
encodedKey: publicKey,
});
const keyGroup = new cloudfront.KeyGroup(this, 'MyKeyGroup', {
items: [
pubKey,
],
});
new cloudfront.CloudFrontWebDistribution(this, 'AnAmazingWebsiteProbably', {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: sourceBucket,
},
behaviors: [
{
isDefaultBehavior: true,
trustedKeyGroups: [
keyGroup,
],
},
],
},
],
});
# Using trusted key groups for Cloudfront Web Distributions.
# source_bucket: s3.Bucket
# public_key: str
pub_key = cloudfront.PublicKey(self, "MyPubKey",
encoded_key=public_key
)
key_group = cloudfront.KeyGroup(self, "MyKeyGroup",
items=[pub_key
]
)
cloudfront.CloudFrontWebDistribution(self, "AnAmazingWebsiteProbably",
origin_configs=[cloudfront.SourceConfiguration(
s3_origin_source=cloudfront.S3OriginConfig(
s3_bucket_source=source_bucket
),
behaviors=[cloudfront.Behavior(
is_default_behavior=True,
trusted_key_groups=[key_group
]
)
]
)
]
)
// Using trusted key groups for Cloudfront Web Distributions.
Bucket sourceBucket;
String publicKey;
PublicKey pubKey = PublicKey.Builder.create(this, "MyPubKey")
.encodedKey(publicKey)
.build();
KeyGroup keyGroup = KeyGroup.Builder.create(this, "MyKeyGroup")
.items(List.of(pubKey))
.build();
CloudFrontWebDistribution.Builder.create(this, "AnAmazingWebsiteProbably")
.originConfigs(List.of(SourceConfiguration.builder()
.s3OriginSource(S3OriginConfig.builder()
.s3BucketSource(sourceBucket)
.build())
.behaviors(List.of(Behavior.builder()
.isDefaultBehavior(true)
.trustedKeyGroups(List.of(keyGroup))
.build()))
.build()))
.build();
// Using trusted key groups for Cloudfront Web Distributions.
Bucket sourceBucket;
string publicKey;
var pubKey = new PublicKey(this, "MyPubKey", new PublicKeyProps {
EncodedKey = publicKey
});
var keyGroup = new KeyGroup(this, "MyKeyGroup", new KeyGroupProps {
Items = new [] { pubKey }
});
new CloudFrontWebDistribution(this, "AnAmazingWebsiteProbably", new CloudFrontWebDistributionProps {
OriginConfigs = new [] { new SourceConfiguration {
S3OriginSource = new S3OriginConfig {
S3BucketSource = sourceBucket
},
Behaviors = new [] { new Behavior {
IsDefaultBehavior = true,
TrustedKeyGroups = new [] { keyGroup }
} }
} }
});
// Using trusted key groups for Cloudfront Web Distributions.
var sourceBucket Bucket
var publicKey string
pubKey := cloudfront.NewPublicKey(this, jsii.String("MyPubKey"), &PublicKeyProps{
EncodedKey: publicKey,
})
keyGroup := cloudfront.NewKeyGroup(this, jsii.String("MyKeyGroup"), &KeyGroupProps{
Items: []IPublicKeyRef{
pubKey,
},
})
cloudfront.NewCloudFrontWebDistribution(this, jsii.String("AnAmazingWebsiteProbably"), &CloudFrontWebDistributionProps{
OriginConfigs: []SourceConfiguration{
&SourceConfiguration{
S3OriginSource: &S3OriginConfig{
S3BucketSource: sourceBucket,
},
Behaviors: []Behavior{
&Behavior{
IsDefaultBehavior: jsii.Boolean(true),
TrustedKeyGroups: []IKeyGroupRef{
keyGroup,
},
},
},
},
},
})
Restrictions
CloudFront supports adding restrictions to your distribution.
See Restricting the Geographic Distribution of Your Content in the CloudFront User Guide.
Example:
// Adding restrictions to a Cloudfront Web Distribution.
declare const sourceBucket: s3.Bucket;
new cloudfront.CloudFrontWebDistribution(this, 'MyDistribution', {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: sourceBucket,
},
behaviors : [ {isDefaultBehavior: true}],
},
],
geoRestriction: cloudfront.GeoRestriction.allowlist('US', 'GB'),
});
# Adding restrictions to a Cloudfront Web Distribution.
# source_bucket: s3.Bucket
cloudfront.CloudFrontWebDistribution(self, "MyDistribution",
origin_configs=[cloudfront.SourceConfiguration(
s3_origin_source=cloudfront.S3OriginConfig(
s3_bucket_source=source_bucket
),
behaviors=[cloudfront.Behavior(is_default_behavior=True)]
)
],
geo_restriction=cloudfront.GeoRestriction.allowlist("US", "GB")
)
// Adding restrictions to a Cloudfront Web Distribution.
Bucket sourceBucket;
CloudFrontWebDistribution.Builder.create(this, "MyDistribution")
.originConfigs(List.of(SourceConfiguration.builder()
.s3OriginSource(S3OriginConfig.builder()
.s3BucketSource(sourceBucket)
.build())
.behaviors(List.of(Behavior.builder().isDefaultBehavior(true).build()))
.build()))
.geoRestriction(GeoRestriction.allowlist("US", "GB"))
.build();
// Adding restrictions to a Cloudfront Web Distribution.
Bucket sourceBucket;
new CloudFrontWebDistribution(this, "MyDistribution", new CloudFrontWebDistributionProps {
OriginConfigs = new [] { new SourceConfiguration {
S3OriginSource = new S3OriginConfig {
S3BucketSource = sourceBucket
},
Behaviors = new [] { new Behavior { IsDefaultBehavior = true } }
} },
GeoRestriction = GeoRestriction.Allowlist("US", "GB")
});
// Adding restrictions to a Cloudfront Web Distribution.
var sourceBucket Bucket
cloudfront.NewCloudFrontWebDistribution(this, jsii.String("MyDistribution"), &CloudFrontWebDistributionProps{
OriginConfigs: []SourceConfiguration{
&SourceConfiguration{
S3OriginSource: &S3OriginConfig{
S3BucketSource: sourceBucket,
},
Behaviors: []Behavior{
&Behavior{
IsDefaultBehavior: jsii.Boolean(true),
},
},
},
},
GeoRestriction: cloudfront.GeoRestriction_Allowlist(jsii.String("US"), jsii.String("GB")),
})
Connection behaviors between CloudFront and your origin
CloudFront provides you even more control over the connection behaviors between CloudFront and your origin. You can now configure the number of connection attempts CloudFront will make to your origin and the origin connection timeout for each attempt.
See Origin Connection Attempts
Example usage:
// Configuring connection behaviors between Cloudfront and your origin
const distribution = new cloudfront.CloudFrontWebDistribution(this, 'MyDistribution', {
originConfigs: [
{
connectionAttempts: 3,
connectionTimeout: Duration.seconds(10),
behaviors: [
{
isDefaultBehavior: true,
},
],
},
],
});
# Configuring connection behaviors between Cloudfront and your origin
distribution = cloudfront.CloudFrontWebDistribution(self, "MyDistribution",
origin_configs=[cloudfront.SourceConfiguration(
connection_attempts=3,
connection_timeout=Duration.seconds(10),
behaviors=[cloudfront.Behavior(
is_default_behavior=True
)
]
)
]
)
// Configuring connection behaviors between Cloudfront and your origin
CloudFrontWebDistribution distribution = CloudFrontWebDistribution.Builder.create(this, "MyDistribution")
.originConfigs(List.of(SourceConfiguration.builder()
.connectionAttempts(3)
.connectionTimeout(Duration.seconds(10))
.behaviors(List.of(Behavior.builder()
.isDefaultBehavior(true)
.build()))
.build()))
.build();
// Configuring connection behaviors between Cloudfront and your origin
var distribution = new CloudFrontWebDistribution(this, "MyDistribution", new CloudFrontWebDistributionProps {
OriginConfigs = new [] { new SourceConfiguration {
ConnectionAttempts = 3,
ConnectionTimeout = Duration.Seconds(10),
Behaviors = new [] { new Behavior {
IsDefaultBehavior = true
} }
} }
});
// Configuring connection behaviors between Cloudfront and your origin
distribution := cloudfront.NewCloudFrontWebDistribution(this, jsii.String("MyDistribution"), &CloudFrontWebDistributionProps{
OriginConfigs: []SourceConfiguration{
&SourceConfiguration{
ConnectionAttempts: jsii.Number(3),
ConnectionTimeout: awscdk.Duration_Seconds(jsii.Number(10)),
Behaviors: []Behavior{
&Behavior{
IsDefaultBehavior: jsii.Boolean(true),
},
},
},
},
})
Origin Fallback
In case the origin source is not available and answers with one of the specified status codes the failover origin source will be used.
// Configuring origin fallback options for the CloudFrontWebDistribution
new cloudfront.CloudFrontWebDistribution(this, 'ADistribution', {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: s3.Bucket.fromBucketName(this, 'aBucket', 'amzn-s3-demo-bucket'),
originPath: '/',
originHeaders: {
'myHeader': '42',
},
originShieldRegion: 'us-west-2',
},
failoverS3OriginSource: {
s3BucketSource: s3.Bucket.fromBucketName(this, 'aBucketFallback', 'amzn-s3-demo-bucket1'),
originPath: '/somewhere',
originHeaders: {
'myHeader2': '21',
},
originShieldRegion: 'us-east-1',
},
failoverCriteriaStatusCodes: [cloudfront.FailoverStatusCode.INTERNAL_SERVER_ERROR],
behaviors: [
{
isDefaultBehavior: true,
},
],
},
],
});
# Configuring origin fallback options for the CloudFrontWebDistribution
cloudfront.CloudFrontWebDistribution(self, "ADistribution",
origin_configs=[cloudfront.SourceConfiguration(
s3_origin_source=cloudfront.S3OriginConfig(
s3_bucket_source=s3.Bucket.from_bucket_name(self, "aBucket", "amzn-s3-demo-bucket"),
origin_path="/",
origin_headers={
"myHeader": "42"
},
origin_shield_region="us-west-2"
),
failover_s3_origin_source=cloudfront.S3OriginConfig(
s3_bucket_source=s3.Bucket.from_bucket_name(self, "aBucketFallback", "amzn-s3-demo-bucket1"),
origin_path="/somewhere",
origin_headers={
"myHeader2": "21"
},
origin_shield_region="us-east-1"
),
failover_criteria_status_codes=[cloudfront.FailoverStatusCode.INTERNAL_SERVER_ERROR],
behaviors=[cloudfront.Behavior(
is_default_behavior=True
)
]
)
]
)
// Configuring origin fallback options for the CloudFrontWebDistribution
// Configuring origin fallback options for the CloudFrontWebDistribution
CloudFrontWebDistribution.Builder.create(this, "ADistribution")
.originConfigs(List.of(SourceConfiguration.builder()
.s3OriginSource(S3OriginConfig.builder()
.s3BucketSource(Bucket.fromBucketName(this, "aBucket", "amzn-s3-demo-bucket"))
.originPath("/")
.originHeaders(Map.of(
"myHeader", "42"))
.originShieldRegion("us-west-2")
.build())
.failoverS3OriginSource(S3OriginConfig.builder()
.s3BucketSource(Bucket.fromBucketName(this, "aBucketFallback", "amzn-s3-demo-bucket1"))
.originPath("/somewhere")
.originHeaders(Map.of(
"myHeader2", "21"))
.originShieldRegion("us-east-1")
.build())
.failoverCriteriaStatusCodes(List.of(FailoverStatusCode.INTERNAL_SERVER_ERROR))
.behaviors(List.of(Behavior.builder()
.isDefaultBehavior(true)
.build()))
.build()))
.build();
// Configuring origin fallback options for the CloudFrontWebDistribution
// Configuring origin fallback options for the CloudFrontWebDistribution
new CloudFrontWebDistribution(this, "ADistribution", new CloudFrontWebDistributionProps {
OriginConfigs = new [] { new SourceConfiguration {
S3OriginSource = new S3OriginConfig {
S3BucketSource = Bucket.FromBucketName(this, "aBucket", "amzn-s3-demo-bucket"),
OriginPath = "/",
OriginHeaders = new Dictionary<string, string> {
{ "myHeader", "42" }
},
OriginShieldRegion = "us-west-2"
},
FailoverS3OriginSource = new S3OriginConfig {
S3BucketSource = Bucket.FromBucketName(this, "aBucketFallback", "amzn-s3-demo-bucket1"),
OriginPath = "/somewhere",
OriginHeaders = new Dictionary<string, string> {
{ "myHeader2", "21" }
},
OriginShieldRegion = "us-east-1"
},
FailoverCriteriaStatusCodes = new [] { FailoverStatusCode.INTERNAL_SERVER_ERROR },
Behaviors = new [] { new Behavior {
IsDefaultBehavior = true
} }
} }
});
// Configuring origin fallback options for the CloudFrontWebDistribution
// Configuring origin fallback options for the CloudFrontWebDistribution
cloudfront.NewCloudFrontWebDistribution(this, jsii.String("ADistribution"), &CloudFrontWebDistributionProps{
OriginConfigs: []SourceConfiguration{
&SourceConfiguration{
S3OriginSource: &S3OriginConfig{
S3BucketSource: s3.Bucket_FromBucketName(this, jsii.String("aBucket"), jsii.String("amzn-s3-demo-bucket")),
OriginPath: jsii.String("/"),
OriginHeaders: map[string]*string{
"myHeader": jsii.String("42"),
},
OriginShieldRegion: jsii.String("us-west-2"),
},
FailoverS3OriginSource: &S3OriginConfig{
S3BucketSource: s3.Bucket_*FromBucketName(this, jsii.String("aBucketFallback"), jsii.String("amzn-s3-demo-bucket1")),
OriginPath: jsii.String("/somewhere"),
OriginHeaders: map[string]*string{
"myHeader2": jsii.String("21"),
},
OriginShieldRegion: jsii.String("us-east-1"),
},
FailoverCriteriaStatusCodes: []FailoverStatusCode{
cloudfront.FailoverStatusCode_INTERNAL_SERVER_ERROR,
},
Behaviors: []Behavior{
&Behavior{
IsDefaultBehavior: jsii.Boolean(true),
},
},
},
},
})
KeyGroup & PublicKey API
You can create a key group to use with CloudFront signed URLs and signed cookies You can add public keys to use with CloudFront features such as signed URLs, signed cookies, and field-level encryption.
The following example command uses OpenSSL to generate an RSA key pair with a length of 2048 bits and save to the file named private_key.pem.
openssl genrsa -out private_key.pem 2048
The resulting file contains both the public and the private key. The following example command extracts the public key from the file named private_key.pem and stores it in public_key.pem.
openssl rsa -pubout -in private_key.pem -out public_key.pem
Note: Don't forget to copy/paste the contents of public_key.pem file including -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY----- lines into encodedKey parameter when creating a PublicKey.
Example:
// Create a key group to use with CloudFront signed URLs and signed cookies.
new cloudfront.KeyGroup(this, 'MyKeyGroup', {
items: [
new cloudfront.PublicKey(this, 'MyPublicKey', {
encodedKey: '...', // contents of public_key.pem file
// comment: 'Key is expiring on ...',
}),
],
// comment: 'Key group containing public keys ...',
});
# Create a key group to use with CloudFront signed URLs and signed cookies.
cloudfront.KeyGroup(self, "MyKeyGroup",
items=[
cloudfront.PublicKey(self, "MyPublicKey",
encoded_key="..."
)
]
)
// Create a key group to use with CloudFront signed URLs and signed cookies.
// Create a key group to use with CloudFront signed URLs and signed cookies.
KeyGroup.Builder.create(this, "MyKeyGroup")
.items(List.of(
PublicKey.Builder.create(this, "MyPublicKey")
.encodedKey("...")
.build()))
.build();
// Create a key group to use with CloudFront signed URLs and signed cookies.
// Create a key group to use with CloudFront signed URLs and signed cookies.
new KeyGroup(this, "MyKeyGroup", new KeyGroupProps {
Items = new [] {
new PublicKey(this, "MyPublicKey", new PublicKeyProps {
EncodedKey = "..."
}) }
});
// Create a key group to use with CloudFront signed URLs and signed cookies.
// Create a key group to use with CloudFront signed URLs and signed cookies.
cloudfront.NewKeyGroup(this, jsii.String("MyKeyGroup"), &KeyGroupProps{
Items: []IPublicKeyRef{
cloudfront.NewPublicKey(this, jsii.String("MyPublicKey"), &PublicKeyProps{
EncodedKey: jsii.String("..."),
}),
},
})
When using a CloudFront PublicKey, only the comment field can be updated after creation. Fields such as encodedKey and publicKeyName are immutable, as outlined in the API Reference. Attempting to modify these fields will result in an error:
Resource handler returned message: "Invalid request provided: AWS::CloudFront::PublicKey"
To update the encodedKey, you must change the ID of the public key resource in your template. This causes CloudFormation to create a new cloudfront.PublicKey resource and delete the old one during the next deployment.
Example:
// Step 1: Original deployment
const originalKey = new cloudfront.PublicKey(this, 'MyPublicKeyV1', {
encodedKey: '...', // contents of original public_key.pem file
});
# Step 1: Original deployment
original_key = cloudfront.PublicKey(self, "MyPublicKeyV1",
encoded_key="..."
)
// Step 1: Original deployment
PublicKey originalKey = PublicKey.Builder.create(this, "MyPublicKeyV1")
.encodedKey("...")
.build();
// Step 1: Original deployment
var originalKey = new PublicKey(this, "MyPublicKeyV1", new PublicKeyProps {
EncodedKey = "..."
});
// Step 1: Original deployment
originalKey := cloudfront.NewPublicKey(this, jsii.String("MyPublicKeyV1"), &PublicKeyProps{
EncodedKey: jsii.String("..."),
})
Regenerate a new key and change the construct id in the code:
// Step 2: In a subsequent deployment, create a new key with a different ID
const updatedKey = new cloudfront.PublicKey(this, 'MyPublicKeyV2', {
encodedKey: '...', // contents of new public_key.pem file
});
# Step 2: In a subsequent deployment, create a new key with a different ID
updated_key = cloudfront.PublicKey(self, "MyPublicKeyV2",
encoded_key="..."
)
// Step 2: In a subsequent deployment, create a new key with a different ID
PublicKey updatedKey = PublicKey.Builder.create(this, "MyPublicKeyV2")
.encodedKey("...")
.build();
// Step 2: In a subsequent deployment, create a new key with a different ID
var updatedKey = new PublicKey(this, "MyPublicKeyV2", new PublicKeyProps {
EncodedKey = "..."
});
// Step 2: In a subsequent deployment, create a new key with a different ID
updatedKey := cloudfront.NewPublicKey(this, jsii.String("MyPublicKeyV2"), &PublicKeyProps{
EncodedKey: jsii.String("..."),
})
See:
Types
| Name | Kind | Summary |
|---|---|---|
CachePolicy | Construct (L2) | A Cache Policy configuration. |
CloudFrontWebDistribution | Construct (L2) | Amazon CloudFront is a global content delivery network (CDN) service that securely delivers data, videos, applications, and APIs to your viewers with low latency and high transfer speeds. |
Distribution | Construct (L2) | A CloudFront distribution with associated origin(s) and caching behavior(s). |
Function | Construct (L2) | A CloudFront Function. |
FunctionUrlOriginAccessControl | Construct (L2) | An Origin Access Control for Lambda Function URLs. |
KeyGroup | Construct (L2) | A Key Group configuration. |
KeyValueStore | Construct (L2) | A CloudFront Key Value Store. |
MediaPackageV2OriginAccessControl | Construct (L2) | An Origin Access Control for AWS Elemental MediaPackage V2 origins. |
OriginAccessIdentity | Construct (L2) | An origin access identity is a special CloudFront user that you can associate with Amazon S3 origins, so that you can secure all or just some of your Amazon S3 content. |
OriginRequestPolicy | Construct (L2) | A Origin Request Policy configuration. |
PublicKey | Construct (L2) | A Public Key Configuration. |
RealtimeLogConfig | Construct (L2) | A Realtime Log Config configuration. |
ResponseHeadersPolicy | Construct (L2) | A Response Headers Policy configuration. |
S3OriginAccessControl | Construct (L2) | An Origin Access Control for Amazon S3 origins. |
VpcOrigin | Construct (L2) | A CloudFront VPC Origin configuration. |
CfnAnycastIpList | Construct (L1) | An Anycast static IP list. |
CfnCachePolicy | Construct (L1) | A cache policy. |
CfnCloudFrontOriginAccessIdentity | Construct (L1) | The request to create a new origin access identity (OAI). |
CfnConnectionFunction | Construct (L1) | A connection function. |
CfnConnectionGroup | Construct (L1) | The connection group for your distribution tenants. |
CfnContinuousDeploymentPolicy | Construct (L1) | Creates a continuous deployment policy that routes a subset of production traffic from a primary distribution to a staging distribution. |
CfnDistribution | Construct (L1) | A distribution tells CloudFront where you want content to be delivered from, and the details about how to track and manage content delivery. |
CfnDistributionTenant | Construct (L1) | The distribution tenant. |
CfnFieldLevelEncryptionProfile | Construct (L1) | Resource Type definition for AWS::CloudFront::FieldLevelEncryptionProfile. |
CfnFunction | Construct (L1) | Creates a CloudFront function. |
CfnKeyGroup | Construct (L1) | A key group. |
CfnKeyValueStore | Construct (L1) | The key value store. |
CfnMonitoringSubscription | Construct (L1) | A monitoring subscription. |
CfnOriginAccessControl | Construct (L1) | Creates a new origin access control in CloudFront. |
CfnOriginRequestPolicy | Construct (L1) | An origin request policy. |
CfnPublicKey | Construct (L1) | A public key that you can use with signed URLs and signed cookies , or with field-level encryption . |
CfnRealtimeLogConfig | Construct (L1) | A real-time log configuration. |
CfnResponseHeadersPolicy | Construct (L1) | A response headers policy. |
CfnStreamingDistribution | Construct (L1) | This resource is deprecated. |
CfnTrustStore | Construct (L1) | A trust store. |
CfnVpcOrigin | Construct (L1) | An Amazon CloudFront VPC origin. |
AccessLevel | Enum | The level of permissions granted to the CloudFront Distribution when configuring OAC. |
AddBehaviorOptions | Struct | Options for adding a new behavior to a Distribution. |
AllowedMethods | Class | The HTTP methods that the Behavior will accept requests on. |
AssetImportSource | Class | An import source from a local file. |
Behavior | Struct | A CloudFront behavior wrapper. |
BehaviorOptions | Struct | Options for creating a new behavior. |
CacheCookieBehavior | Class | Determines whether any cookies in viewer requests are included in the cache key and automatically included in requests that CloudFront sends to the origin. |
CachedMethods | Class | The HTTP methods that the Behavior will cache requests on. |
CacheHeaderBehavior | Class | Determines whether any HTTP headers are included in the cache key and automatically included in requests that CloudFront sends to the origin. |
CachePolicyProps | Struct | Properties for creating a Cache Policy. |
CacheQueryStringBehavior | Class | Determines whether any URL query strings in viewer requests are included in the cache key and automatically included in requests that CloudFront sends to the origin. |
CfnAnycastIpList.AnycastIpListProperty | Struct | An Anycast static IP list. |
CfnAnycastIpList.IpamCidrConfigProperty | Struct | Configuration for an IPAM CIDR that defines a specific IP address range, IPAM pool, and associated Anycast IP address. |
CfnAnycastIpList.IpamCidrConfigResultProperty | Struct | The result for the IPAM CIDR that defines a specific IP address range, IPAM pool, and associated Anycast IP address. |
CfnAnycastIpList.TagsProperty | Struct | A complex type that contains zero or more Tag elements. |
CfnAnycastIpListProps | Struct | Properties for defining a CfnAnycastIpList. |
CfnCachePolicy.CachePolicyConfigProperty | Struct | A cache policy configuration. |
CfnCachePolicy.CookiesConfigProperty | Struct | An object that determines whether any cookies in viewer requests (and if so, which cookies) are included in the cache key and in requests that CloudFront sends to the origin. |
CfnCachePolicy.HeadersConfigProperty | Struct | An object that determines whether any HTTP headers (and if so, which headers) are included in the cache key and in requests that CloudFront sends to the origin. |
CfnCachePolicy.ParametersInCacheKeyAndForwardedToOriginProperty | Struct | This object determines the values that CloudFront includes in the cache key. |
CfnCachePolicy.QueryStringsConfigProperty | Struct | An object that determines whether any URL query strings in viewer requests (and if so, which query strings) are included in the cache key and in requests that CloudFront sends to the origin. |
CfnCachePolicyProps | Struct | Properties for defining a CfnCachePolicy. |
CfnCloudFrontOriginAccessIdentity.CloudFrontOriginAccessIdentityConfigProperty | Struct | Origin access identity configuration. |
CfnCloudFrontOriginAccessIdentityProps | Struct | Properties for defining a CfnCloudFrontOriginAccessIdentity. |
CfnConnectionFunction.ConnectionFunctionConfigProperty | Struct | Contains configuration information about a CloudFront function. |
CfnConnectionFunction.KeyValueStoreAssociationProperty | Struct | The key value store association. |
CfnConnectionFunctionProps | Struct | Properties for defining a CfnConnectionFunction. |
CfnConnectionGroupProps | Struct | Properties for defining a CfnConnectionGroup. |
CfnContinuousDeploymentPolicy.ContinuousDeploymentPolicyConfigProperty | Struct | Contains the configuration for a continuous deployment policy. |
CfnContinuousDeploymentPolicy.SessionStickinessConfigProperty | Struct | Session stickiness provides the ability to define multiple requests from a single viewer as a single session. |
CfnContinuousDeploymentPolicy.SingleHeaderConfigProperty | Struct | Determines which HTTP requests are sent to the staging distribution. |
CfnContinuousDeploymentPolicy.SingleHeaderPolicyConfigProperty | Struct | Defines a single header policy for a CloudFront distribution. |
CfnContinuousDeploymentPolicy.SingleWeightConfigProperty | Struct | This configuration determines the percentage of HTTP requests that are sent to the staging distribution. |
CfnContinuousDeploymentPolicy.SingleWeightPolicyConfigProperty | Struct | Configure a policy that CloudFront uses to route requests to different origins or use different cache settings, based on the weight assigned to each option. |
CfnContinuousDeploymentPolicy.TrafficConfigProperty | Struct | The traffic configuration of your continuous deployment. |
CfnContinuousDeploymentPolicyProps | Struct | Properties for defining a CfnContinuousDeploymentPolicy. |
CfnDistribution.CacheBehaviorProperty | Struct | A complex type that describes how CloudFront processes requests. |
CfnDistribution.CacheTagConfigProperty | Struct | A complex type that specifies the HTTP header name from which CloudFront extracts cache tags from origin responses. |
CfnDistribution.ConnectionFunctionAssociationProperty | Struct | A connection function association. |
CfnDistribution.CookiesProperty | Struct | This field is deprecated. |
CfnDistribution.CustomErrorResponseProperty | Struct | A complex type that controls:. |
CfnDistribution.CustomOriginConfigProperty | Struct | A custom origin. |
CfnDistribution.DefaultCacheBehaviorProperty | Struct | A complex type that describes the default cache behavior if you don't specify a CacheBehavior element or if request URLs don't match any of the values of PathPattern in CacheBehavior elements. |
CfnDistribution.DefinitionProperty | Struct | The value that you assigned to the parameter. |
CfnDistribution.DistributionConfigProperty | Struct | A distribution configuration. |
CfnDistribution.ForwardedValuesProperty | Struct | > This field only supports standard distributions. |
CfnDistribution.FunctionAssociationProperty | Struct | A CloudFront function that is associated with a cache behavior in a CloudFront distribution. |
CfnDistribution.GeoRestrictionProperty | Struct | A complex type that controls the countries in which your content is distributed. |
CfnDistribution.GrpcConfigProperty | Struct | Amazon CloudFront supports gRPC, an open-source remote procedure call (RPC) framework built on HTTP/2. |
CfnDistribution.LambdaFunctionAssociationProperty | Struct | A complex type that contains a Lambda@Edge function association. |
CfnDistribution.LegacyCustomOriginProperty | Struct | A custom origin. |
CfnDistribution.LegacyS3OriginProperty | Struct | The origin as an Amazon S3 bucket. |
CfnDistribution.LoggingProperty | Struct | A complex type that specifies whether access logs are written for the distribution. |
CfnDistribution.OriginCustomHeaderProperty | Struct | A complex type that contains HeaderName and HeaderValue elements, if any, for this distribution. |
CfnDistribution.OriginGroupFailoverCriteriaProperty | Struct | A complex data type that includes information about the failover criteria for an origin group, including the status codes for which CloudFront will failover from the primary origin to the second origin. |
CfnDistribution.OriginGroupMemberProperty | Struct | An origin in an origin group. |
CfnDistribution.OriginGroupMembersProperty | Struct | A complex data type for the origins included in an origin group. |
CfnDistribution.OriginGroupProperty | Struct | An origin group includes two origins (a primary origin and a secondary origin to failover to) and a failover criteria that you specify. |
CfnDistribution.OriginGroupsProperty | Struct | A complex data type for the origin groups specified for a distribution. |
CfnDistribution.OriginMtlsConfigProperty | Struct | Configures mutual TLS authentication between CloudFront and your origin server. |
CfnDistribution.OriginProperty | Struct | An origin. |
CfnDistribution.OriginShieldProperty | Struct | CloudFront Origin Shield. |
CfnDistribution.ParameterDefinitionProperty | Struct | A list of parameter values to add to the resource. |
CfnDistribution.RestrictionsProperty | Struct | A complex type that identifies ways in which you want to restrict distribution of your content. |
CfnDistribution.S3OriginConfigProperty | Struct | A complex type that contains information about the Amazon S3 origin. |
CfnDistribution.StatusCodesProperty | Struct | A complex data type for the status codes that you specify that, when returned by a primary origin, trigger CloudFront to failover to a second origin. |
CfnDistribution.StringSchemaProperty | Struct | |
CfnDistribution.TenantConfigProperty | Struct | > This field only supports multi-tenant distributions. |
CfnDistribution.TrustStoreConfigProperty | Struct | A trust store configuration. |
CfnDistribution.ViewerCertificateProperty | Struct | A complex type that determines the distribution's SSL/TLS configuration for communicating with viewers. |
CfnDistribution.ViewerMtlsConfigProperty | Struct | A viewer mTLS configuration. |
CfnDistribution.VpcOriginConfigProperty | Struct | An Amazon CloudFront VPC origin configuration. |
CfnDistributionProps | Struct | Properties for defining a CfnDistribution. |
CfnDistributionTenant.CertificateProperty | Struct | The Certificate Manager (ACM) certificate associated with your distribution. |
CfnDistributionTenant.CustomizationsProperty | Struct | Customizations for the distribution tenant. |
CfnDistributionTenant.DomainResultProperty | Struct | The details about the domain result. |
CfnDistributionTenant.GeoRestrictionCustomizationProperty | Struct | The customizations that you specified for the distribution tenant for geographic restrictions. |
CfnDistributionTenant.ManagedCertificateRequestProperty | Struct | An object that represents the request for the Amazon CloudFront managed ACM certificate. |
CfnDistributionTenant.ParameterProperty | Struct | A list of parameter values to add to the resource. |
CfnDistributionTenant.WebAclCustomizationProperty | Struct | The AWS WAF web ACL customization specified for the distribution tenant. |
CfnDistributionTenantProps | Struct | Properties for defining a CfnDistributionTenant. |
CfnFieldLevelEncryptionProfile.EncryptionEntityProperty | Struct | A public key, its provider identity, and the field patterns CloudFront encrypts with that key. |
CfnFieldLevelEncryptionProfile.FieldLevelEncryptionProfileConfigProperty | Struct | The configuration of a field-level encryption profile. |
CfnFieldLevelEncryptionProfileProps | Struct | Properties for defining a CfnFieldLevelEncryptionProfile. |
CfnFunction.FunctionConfigProperty | Struct | Contains configuration information about a CloudFront function. |
CfnFunction.FunctionMetadataProperty | Struct | Contains metadata about a CloudFront function. |
CfnFunction.KeyValueStoreAssociationProperty | Struct | The key value store association. |
CfnFunctionProps | Struct | Properties for defining a CfnFunction. |
CfnKeyGroup.KeyGroupConfigProperty | Struct | A key group configuration. |
CfnKeyGroupProps | Struct | Properties for defining a CfnKeyGroup. |
CfnKeyValueStore.ImportSourceProperty | Struct | The import source for the key value store. |
CfnKeyValueStoreProps | Struct | Properties for defining a CfnKeyValueStore. |
CfnMonitoringSubscription.MonitoringSubscriptionProperty | Struct | A monitoring subscription. |
CfnMonitoringSubscription.RealtimeMetricsSubscriptionConfigProperty | Struct | A subscription configuration for additional CloudWatch metrics. |
CfnMonitoringSubscriptionProps | Struct | Properties for defining a CfnMonitoringSubscription. |
CfnOriginAccessControl.OriginAccessControlConfigProperty | Struct | Creates a new origin access control in CloudFront. |
CfnOriginAccessControlProps | Struct | Properties for defining a CfnOriginAccessControl. |
CfnOriginRequestPolicy.CookiesConfigProperty | Struct | An object that determines whether any cookies in viewer requests (and if so, which cookies) are included in requests that CloudFront sends to the origin. |
CfnOriginRequestPolicy.HeadersConfigProperty | Struct | An object that determines whether any HTTP headers (and if so, which headers) are included in requests that CloudFront sends to the origin. |
CfnOriginRequestPolicy.OriginRequestPolicyConfigProperty | Struct | An origin request policy configuration. |
CfnOriginRequestPolicy.QueryStringsConfigProperty | Struct | An object that determines whether any URL query strings in viewer requests (and if so, which query strings) are included in requests that CloudFront sends to the origin. |
CfnOriginRequestPolicyProps | Struct | Properties for defining a CfnOriginRequestPolicy. |
CfnPublicKey.PublicKeyConfigProperty | Struct | Configuration information about a public key that you can use with signed URLs and signed cookies , or with field-level encryption . |
CfnPublicKeyProps | Struct | Properties for defining a CfnPublicKey. |
CfnRealtimeLogConfig.EndPointProperty | Struct | Contains information about the Amazon Kinesis data stream where you are sending real-time log data for this real-time log configuration. |
CfnRealtimeLogConfig.KinesisStreamConfigProperty | Struct | Contains information about the Amazon Kinesis data stream where you are sending real-time log data. |
CfnRealtimeLogConfigProps | Struct | Properties for defining a CfnRealtimeLogConfig. |
CfnResponseHeadersPolicy.AccessControlAllowHeadersProperty | Struct | A list of HTTP header names that CloudFront includes as values for the Access-Control-Allow-Headers HTTP response header. |
CfnResponseHeadersPolicy.AccessControlAllowMethodsProperty | Struct | A list of HTTP methods that CloudFront includes as values for the Access-Control-Allow-Methods HTTP response header. |
CfnResponseHeadersPolicy.AccessControlAllowOriginsProperty | Struct | A list of origins (domain names) that CloudFront can use as the value for the Access-Control-Allow-Origin HTTP response header. |
CfnResponseHeadersPolicy.AccessControlExposeHeadersProperty | Struct | A list of HTTP headers that CloudFront includes as values for the Access-Control-Expose-Headers HTTP response header. |
CfnResponseHeadersPolicy.ContentSecurityPolicyProperty | Struct | The policy directives and their values that CloudFront includes as values for the Content-Security-Policy HTTP response header. |
CfnResponseHeadersPolicy.ContentTypeOptionsProperty | Struct | Determines whether CloudFront includes the X-Content-Type-Options HTTP response header with its value set to nosniff . |
CfnResponseHeadersPolicy.CorsConfigProperty | Struct | A configuration for a set of HTTP response headers that are used for cross-origin resource sharing (CORS). |
CfnResponseHeadersPolicy.CustomHeaderProperty | Struct | An HTTP response header name and its value. |
CfnResponseHeadersPolicy.CustomHeadersConfigProperty | Struct | A list of HTTP response header names and their values. |
CfnResponseHeadersPolicy.FrameOptionsProperty | Struct | Determines whether CloudFront includes the X-Frame-Options HTTP response header and the header's value. |
CfnResponseHeadersPolicy.ReferrerPolicyProperty | Struct | Determines whether CloudFront includes the Referrer-Policy HTTP response header and the header's value. |
CfnResponseHeadersPolicy.RemoveHeaderProperty | Struct | The name of an HTTP header that CloudFront removes from HTTP responses to requests that match the cache behavior that this response headers policy is attached to. |
CfnResponseHeadersPolicy.RemoveHeadersConfigProperty | Struct | A list of HTTP header names that CloudFront removes from HTTP responses to requests that match the cache behavior that this response headers policy is attached to. |
CfnResponseHeadersPolicy.ResponseHeadersPolicyConfigProperty | Struct | A response headers policy configuration. |
CfnResponseHeadersPolicy.SecurityHeadersConfigProperty | Struct | A configuration for a set of security-related HTTP response headers. |
CfnResponseHeadersPolicy.ServerTimingHeadersConfigProperty | Struct | A configuration for enabling the Server-Timing header in HTTP responses sent from CloudFront. |
CfnResponseHeadersPolicy.StrictTransportSecurityProperty | Struct | Determines whether CloudFront includes the Strict-Transport-Security HTTP response header and the header's value. |
CfnResponseHeadersPolicy.XSSProtectionProperty | Struct | Determines whether CloudFront includes the X-XSS-Protection HTTP response header and the header's value. |
CfnResponseHeadersPolicyProps | Struct | Properties for defining a CfnResponseHeadersPolicy. |
CfnStreamingDistribution.LoggingProperty | Struct | A complex type that controls whether access logs are written for the streaming distribution. |
CfnStreamingDistribution.S3OriginProperty | Struct | A complex type that contains information about the Amazon S3 bucket from which you want CloudFront to get your media files for distribution. |
CfnStreamingDistribution.StreamingDistributionConfigProperty | Struct | The RTMP distribution's configuration information. |
CfnStreamingDistribution.TrustedSignersProperty | Struct | A list of AWS accounts whose public keys CloudFront can use to verify the signatures of signed URLs and signed cookies. |
CfnStreamingDistributionProps | Struct | Properties for defining a CfnStreamingDistribution. |
CfnTrustStore.CaCertificatesBundleS3LocationProperty | Struct | The CA certificates bundle location in Amazon S3. |
CfnTrustStore.CaCertificatesBundleSourceProperty | Struct | A CA certificates bundle source. |
CfnTrustStoreProps | Struct | Properties for defining a CfnTrustStore. |
CfnVpcOrigin.VpcOriginEndpointConfigProperty | Struct | An Amazon CloudFront VPC origin endpoint configuration. |
CfnVpcOriginProps | Struct | Properties for defining a CfnVpcOrigin. |
CloudFrontAllowedCachedMethods | Enum | Enums for the methods CloudFront can cache. |
CloudFrontAllowedMethods | Enum | An enum for the supported methods to a CloudFront distribution. |
CloudFrontWebDistributionAttributes | Struct | Attributes used to import a Distribution. |
CloudFrontWebDistributionProps | Struct | |
CustomOriginConfig | Struct | A custom origin configuration. |
DistributionAttributes | Struct | Attributes used to import a Distribution. |
DistributionGrants | Facade | Collection of grant methods for a IDistributionRef. |
DistributionProps | Struct | Properties for a Distribution. |
EdgeLambda | Struct | Represents a Lambda function version and event type when using Lambda@Edge. |
Endpoint | Class | Represents the endpoints available for targetting within a realtime log config resource. |
ErrorResponse | Struct | Options for configuring custom error responses. |
FailoverStatusCode | Enum | HTTP status code to failover to second origin. |
FileCodeOptions | Struct | Options when reading the function's code from an external file. |
FunctionAssociation | Struct | Represents a CloudFront function and event type when using CF Functions. |
FunctionAttributes | Struct | Attributes of an existing CloudFront Function to import it. |
FunctionCode | Class | Represents the function's source code. |
FunctionEventType | Enum | The type of events that a CloudFront function can be invoked in response to. |
FunctionProps | Struct | Properties for creating a CloudFront Function. |
FunctionRuntime | Class | The function's runtime environment version. |
FunctionUrlOriginAccessControlProps | Struct | Properties for creating a Lambda Function URL Origin Access Control resource. |
GeoRestriction | Class | Controls the countries in which content is distributed. |
HeadersFrameOption | Enum | Enum representing possible values of the X-Frame-Options HTTP response header. |
HeadersReferrerPolicy | Enum | Enum representing possible values of the Referrer-Policy HTTP response header. |
HttpVersion | Enum | The HTTP version(s) to enable on the distribution. |
ICachePolicy | Interface | Represents a Cache Policy. |
IDistribution | Interface | Interface for CloudFront distributions. |
IFunction | Interface | Represents a CloudFront Function. |
IKeyGroup | Interface | Represents a Key Group. |
IKeyValueStore | Interface | A CloudFront Key Value Store. |
ImportSource | Class | The data to be imported to the key value store. |
InlineImportSource | Class | An import source from an inline string. |
IOrigin | Interface | Represents the concept of a CloudFront Origin. |
IOriginAccessControl | Interface | Represents a CloudFront Origin Access Control. |
IOriginAccessIdentity | Interface | Interface for CloudFront OriginAccessIdentity. |
IOriginRequestPolicy | Interface | Represents a Origin Request Policy. |
IPublicKey | Interface | Represents a Public Key. |
IRealtimeLogConfig | Interface | Represents Realtime Log Configuration. |
IResponseHeadersPolicy | Interface | Represents a response headers policy. |
IVpcOrigin | Interface | Represents a VPC origin. |
KeyGroupProps | Struct | Properties for creating a Public Key. |
KeyValueStoreProps | Struct | The properties to create a Key Value Store. |
LambdaEdgeEventType | Enum | The type of events that a Lambda@Edge function can be invoked in response to. |
LambdaFunctionAssociation | Struct | |
LoggingConfiguration | Struct | Logging configuration for incoming requests. |
MediaPackageV2OriginAccessControlProps | Struct | Properties for creating a MediaPackage V2 Origin Access Control resource. |
OriginAccessControlBaseProps | Struct | Common properties for creating a Origin Access Control resource. |
OriginAccessControlOriginType | Enum | Origin types supported by Origin Access Control. |
OriginAccessIdentityProps | Struct | Properties of CloudFront OriginAccessIdentity. |
OriginBase | Class | Represents a distribution origin, that describes the Amazon S3 bucket, HTTP server (for example, a web server), Amazon MediaStore, or other server from which CloudFront gets your files. |
OriginBindConfig | Struct | The struct returned from IOrigin.bind. |
OriginBindOptions | Struct | Options passed to Origin.bind(). |
OriginFailoverConfig | Struct | The failover configuration used for Origin Groups, returned in OriginBindConfig.failoverConfig. |
OriginIpAddressType | Enum | The IP address type for the origin. |
OriginOptions | Struct | Options to define an Origin. |
OriginProps | Struct | Properties to define an Origin. |
OriginProtocolPolicy | Enum | Defines what protocols CloudFront will use to connect to an origin. |
OriginRequestCookieBehavior | Class | Determines whether any cookies in viewer requests (and if so, which cookies) are included in requests that CloudFront sends to the origin. |
OriginRequestHeaderBehavior | Class | Determines whether any HTTP headers (and if so, which headers) are included in requests that CloudFront sends to the origin. |
OriginRequestPolicyProps | Struct | Properties for creating a Origin Request Policy. |
OriginRequestQueryStringBehavior | Class | Determines whether any URL query strings in viewer requests (and if so, which query strings) are included in requests that CloudFront sends to the origin. |
OriginSelectionCriteria | Enum | The selection criteria for the origin group. |
OriginSslPolicy | Enum | |
PriceClass | Enum | The price class determines how many edge locations CloudFront will use for your distribution. |
PublicKeyProps | Struct | Properties for creating a Public Key. |
RealtimeLogConfigProps | Struct | Properties for defining a RealtimeLogConfig resource. |
ResponseCustomHeader | Struct | An HTTP response header name and its value. |
ResponseCustomHeadersBehavior | Struct | Configuration for a set of HTTP response headers that are sent for requests that match a cache behavior that’s associated with this response headers policy. |
ResponseHeadersContentSecurityPolicy | Struct | The policy directives and their values that CloudFront includes as values for the Content-Security-Policy HTTP response header. |
ResponseHeadersContentTypeOptions | Struct | Determines whether CloudFront includes the X-Content-Type-Options HTTP response header with its value set to nosniff. |
ResponseHeadersCorsBehavior | Struct | Configuration for a set of HTTP response headers that are used for cross-origin resource sharing (CORS). |
ResponseHeadersFrameOptions | Struct | Determines whether CloudFront includes the X-Frame-Options HTTP response header and the header’s value. |
ResponseHeadersPolicyProps | Struct | Properties for creating a Response Headers Policy. |
ResponseHeadersReferrerPolicy | Struct | Determines whether CloudFront includes the Referrer-Policy HTTP response header and the header’s value. |
ResponseHeadersStrictTransportSecurity | Struct | Determines whether CloudFront includes the Strict-Transport-Security HTTP response header and the header’s value. |
ResponseHeadersXSSProtection | Struct | Determines whether CloudFront includes the X-XSS-Protection HTTP response header and the header’s value. |
ResponseSecurityHeadersBehavior | Struct | Configuration for a set of security-related HTTP response headers. |
S3ImportSource | Class | An import source from an S3 object. |
S3OriginAccessControlProps | Struct | Properties for creating a S3 Origin Access Control resource. |
S3OriginConfig | Struct | S3 origin configuration for CloudFront. |
SecurityPolicyProtocol | Enum | The minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections. |
Signing | Class | Options for how CloudFront signs requests. |
SigningBehavior | Enum | Options for which requests CloudFront signs. |
SigningProtocol | Enum | The signing protocol of the Origin Access Control. |
SourceConfiguration | Struct | A source configuration is a wrapper for CloudFront origins and behaviors. |
SSLMethod | Enum | The SSL method CloudFront will use for your distribution. |
ViewerCertificate | Class | Viewer certificate configuration class. |
ViewerCertificateOptions | Struct | |
ViewerProtocolPolicy | Enum | How HTTPs should be handled with your distribution. |
VpcOriginAttributes | Struct | The properties to import from the VPC origin. |
VpcOriginEndpoint | Class | Represents the VPC origin endpoint. |
VpcOriginOptions | Struct | VPC origin endpoint configuration. |
VpcOriginProps | Struct | VPC origin endpoint configuration. |