# 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.Distribution.html) API replaces the [`CloudFrontWebDistribution`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CloudFrontWebDistribution.html) API which is now deprecated. The [`Distribution`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.Distribution.html) 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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/DownloadDistS3AndCustomOrigins.html#using-s3-as-origin)).

TypeScript:

```ts
// 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
  },
});
```

Python:

```python
# 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)
    )
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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)
    }
});
```

Golang:

```go
// 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`](https://github.com/aws/aws-cdk/blob/main/packages/aws-cdk-lib/aws-cloudfront-origins/README.md) 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.

TypeScript:

```ts
// 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) },
});
```

Python:

```python
# 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))
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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) }
});
```

Golang:

```go
// 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.

TypeScript:

```ts
// Creates a distribution from an HTTP endpoint
new cloudfront.Distribution(this, 'myDist', {
  defaultBehavior: { origin: new origins.HttpOrigin('www.example.com') },
});
```

Python:

```python
# Creates a distribution from an HTTP endpoint
cloudfront.Distribution(self, "myDist",
    default_behavior=cloudfront.BehaviorOptions(origin=origins.HttpOrigin("www.example.com"))
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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") }
});
```

Golang:

```go
// 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

TypeScript:

```ts
// 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'
        },
    },
});
```

Python:

```python
# 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"
        )
    )
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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"
        }
    }
});
```

Golang:

```go
// 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.

TypeScript:

```ts
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'
    },
});
```

Python:

```python
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"
    )
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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"
    }
});
```

Golang:

```go
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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/managed-cloudfront-certificates.html#complete-domain-ownership)

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

TypeScript:

```ts
// 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',
    },
});
```

Python:

```python
# 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"
    )
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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"
    }
});
```

Golang:

```go
// 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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/managed-cloudfront-certificates.html#complete-domain-ownership) 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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/managed-cloudfront-certificates.html#point-domains-to-cloudfront) 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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-vpc-origins.html).

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.

TypeScript:

```ts
// 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,
});
```

Python:

```python
# 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
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
});
```

Golang:

```go
// 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.

TypeScript:

```ts
// 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,
});
```

Python:

```python
# 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
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
});
```

Golang:

```go
// 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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/alternate-domain-names-move.html).

1. Deploy the stack with the target distribution. The `certificate` property must be specified but the `domainNames` should be absent.
2. Move the alternate domain name by running CloudFront `associate-alias` command. For the example and preconditions, see the AWS documentation above.
3. Specify the `domainNames` property 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`.

TypeScript:

```ts
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,
});
```

Python:

```python
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
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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
});
```

Golang:

```go
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.

TypeScript:

```ts
// 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,
  },
});
```

Python:

```python
# 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
    )
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
    }
});
```

Golang:

```go
// 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.

TypeScript:

```ts
// 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,
});
```

Python:

```python
# 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
)
```

Java:

```java
// 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());
```

C# / .NET:

```csharp
// 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
});
```

Golang:

```go
// 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.

TypeScript:

```ts
// 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,
    },
  },
});
```

Python:

```python
# 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
        )
    }
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
        } }
    }
});
```

Golang:

```go
// 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](https://docs.aws.amazon.com/securityhub/latest/userguide/cloudfront-controls.html)
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:

```json
{
  "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:

TypeScript:

```ts
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,
  },
});
```

Python:

```python
# 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
    )
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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
    }
});
```

Golang:

```go
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`.

TypeScript:

```ts
declare const bucketOrigin: origins.S3Origin;
declare const webAcl: wafv2.CfnWebACL;
const distribution = new cloudfront.Distribution(this, 'Distribution', {
  defaultBehavior: { origin: bucketOrigin },
  webAclId: webAcl.attrArn,
});
```

Python:

```python
# 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
)
```

Java:

```java
S3Origin bucketOrigin;
CfnWebACL webAcl;

Distribution distribution = Distribution.Builder.create(this, "Distribution")
        .defaultBehavior(BehaviorOptions.builder().origin(bucketOrigin).build())
        .webAclId(webAcl.getAttrArn())
        .build();
```

C# / .NET:

```csharp
S3Origin bucketOrigin;
CfnWebACL webAcl;

var distribution = new Distribution(this, "Distribution", new DistributionProps {
    DefaultBehavior = new BehaviorOptions { Origin = bucketOrigin },
    WebAclId = webAcl.AttrArn
});
```

Golang:

```go
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.

TypeScript:

```ts
declare const bucketOrigin: origins.S3Origin;
declare const webAcl: wafv2.CfnWebACL;
const distribution = new cloudfront.Distribution(this, 'Distribution', {
  defaultBehavior: { origin: bucketOrigin },
});

distribution.attachWebAclId(webAcl.attrArn);
```

Python:

```python
# 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)
```

Java:

```java
S3Origin bucketOrigin;
CfnWebACL webAcl;

Distribution distribution = Distribution.Builder.create(this, "Distribution")
        .defaultBehavior(BehaviorOptions.builder().origin(bucketOrigin).build())
        .build();

distribution.attachWebAclId(webAcl.getAttrArn());
```

C# / .NET:

```csharp
S3Origin bucketOrigin;
CfnWebACL webAcl;

var distribution = new Distribution(this, "Distribution", new DistributionProps {
    DefaultBehavior = new BehaviorOptions { Origin = bucketOrigin }
});

distribution.AttachWebAclId(webAcl.AttrArn);
```

Golang:

```go
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.

TypeScript:

```ts
// 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,
  },
});
```

Python:

```python
# 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
    )
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
    }
});
```

Golang:

```go
// 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(),
	},
})
```

TypeScript:

```ts
// 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,
  },
});
```

Python:

```python
# 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
    )
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
    }
});
```

Golang:

```go
// 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.

TypeScript:

```ts
// 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,
  },
});
```

Python:

```python
# 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
    )
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
    }
});
```

Golang:

```go
// 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(),
	},
})
```

TypeScript:

```ts
// 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,
  },
});
```

Python:

```python
# 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
    )
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
    }
});
```

Golang:

```go
// 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`.

TypeScript:

```ts
// 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,
  },
});
```

Python:

```python
# 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
    )
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
    }
});
```

Golang:

```go
// 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.

TypeScript:

```ts
// 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,
    ],
  },
});
```

Python:

```python
# 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
        ]
    )
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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 }
    }
});
```

Golang:

```go
// 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:

TypeScript:

```ts
// 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,
      }
    ],
  },
});
```

Python:

```python
# 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
        )
        ]
    )
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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
        } }
    }
});
```

Golang:

```go
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-1` region, regardless of the region of the CloudFront distribution and stack.
> To make it easier to request functions for Lambda@Edge, the `EdgeFunction` construct can be used.
> The `EdgeFunction` construct will automatically request a function in `us-east-1`, regardless of the region of the current stack.
> `EdgeFunction` has the same interface as [`Function`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.Function.html) and can be created and used interchangeably.
> Please note that using `EdgeFunction` requires that the `us-east-1` region 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`.

TypeScript:

```ts
// 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')),
});
```

Python:

```python
# 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"))
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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"))
});
```

Golang:

```go
// 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.

TypeScript:

```ts
// 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',
});
```

Python:

```python
# 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"
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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"
});
```

Golang:

```go
// 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.

TypeScript:

```ts
// 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,
    },
  ],
});
```

Python:

```python
# 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
    )
    ]
)
```

Java:

```java
// 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());
```

C# / .NET:

```csharp
// 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
    } }
});
```

Golang:

```go
// 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.

TypeScript:

```ts
// 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,
      },
    ],
  },
});
```

Python:

```python
# 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
        )
        ]
    )
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
        } }
    }
});
```

Golang:

```go
// 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.

TypeScript:

```ts
// 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,
    }],
  },
});
```

Python:

```python
# 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
        )]
    )
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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
        } }
    }
});
```

Golang:

```go
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.

TypeScript:

```ts
new cloudfront.Function(this, 'Function', {
  code: cloudfront.FunctionCode.fromInline('function handler(event) { return event.request }'),
  runtime: cloudfront.FunctionRuntime.JS_2_0,
  autoPublish: false
});
```

Python:

```python
cloudfront.Function(self, "Function",
    code=cloudfront.FunctionCode.from_inline("function handler(event) { return event.request }"),
    runtime=cloudfront.FunctionRuntime.JS_2_0,
    auto_publish=False
)
```

Java:

```java
Function.Builder.create(this, "Function")
        .code(FunctionCode.fromInline("function handler(event) { return event.request }"))
        .runtime(FunctionRuntime.JS_2_0)
        .autoPublish(false)
        .build();
```

C# / .NET:

```csharp
new Function(this, "Function", new FunctionProps {
    Code = FunctionCode.FromInline("function handler(event) { return event.request }"),
    Runtime = FunctionRuntime.JS_2_0,
    AutoPublish = false
});
```

Golang:

```go
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:

TypeScript:

```ts
// 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,
});
```

Python:

```python
# 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
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
});
```

Golang:

```go
// 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:

TypeScript:

```ts
const store = new cloudfront.KeyValueStore(this, 'KeyValueStore');
```

Python:

```python
store = cloudfront.KeyValueStore(self, "KeyValueStore")
```

Java:

```java
KeyValueStore store = new KeyValueStore(this, "KeyValueStore");
```

C# / .NET:

```csharp
var store = new KeyValueStore(this, "KeyValueStore");
```

Golang:

```go
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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/kvs-with-functions-create-s3-kvp.html).

TypeScript:

```ts
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",
      },
    ],
  })),
});
```

Python:

```python
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"
        }
        ]
    }))
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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"
        } } }
    }))
});
```

Golang:

```go
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:

TypeScript:

```ts
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,
});
```

Python:

```python
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
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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
});
```

Golang:

```go
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.

TypeScript:

```ts
// 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,
});
```

Python:

```python
# 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
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
});
```

Golang:

```go
// 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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/viewing-cloudfront-metrics.html#monitoring-console.distributions) 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.

TypeScript:

```ts
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();
```

Python:

```python
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()
```

Java:

```java
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();
```

C# / .NET:

```csharp
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();
```

Golang:

```go
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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/viewing-cloudfront-metrics.html#monitoring-console.distributions-additional), 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.

TypeScript:

```ts
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();
```

Python:

```python
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()
```

Java:

```java
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();
```

C# / .NET:

```csharp
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();
```

Golang:

```go
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.

TypeScript:

```ts
// 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,
});
```

Python:

```python
# 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
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
});
```

Golang:

```go
// 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.

TypeScript:

```ts
// Using a reference to an imported Distribution
const distribution = cloudfront.Distribution.fromDistributionAttributes(this, 'ImportedDist', {
  domainName: 'd111111abcdef8.cloudfront.net',
  distributionId: '012345ABCDEF',
});
```

Python:

```python
# Using a reference to an imported Distribution
distribution = cloudfront.Distribution.from_distribution_attributes(self, "ImportedDist",
    domain_name="d111111abcdef8.cloudfront.net",
    distribution_id="012345ABCDEF"
)
```

Java:

```java
// Using a reference to an imported Distribution
IDistribution distribution = Distribution.fromDistributionAttributes(this, "ImportedDist", DistributionAttributes.builder()
        .domainName("d111111abcdef8.cloudfront.net")
        .distributionId("012345ABCDEF")
        .build());
```

C# / .NET:

```csharp
// Using a reference to an imported Distribution
var distribution = Distribution.FromDistributionAttributes(this, "ImportedDist", new DistributionAttributes {
    DomainName = "d111111abcdef8.cloudfront.net",
    DistributionId = "012345ABCDEF"
});
```

Golang:

```go
// 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`.

TypeScript:

```ts
declare const distribution: cloudfront.Distribution;
declare const lambdaFn: lambda.Function;
distribution.grant(lambdaFn, 'cloudfront:ListInvalidations', 'cloudfront:GetInvalidation');
distribution.grantCreateInvalidation(lambdaFn);
```

Python:

```python
# distribution: cloudfront.Distribution
# lambda_fn: lambda.Function

distribution.grant(lambda_fn, "cloudfront:ListInvalidations", "cloudfront:GetInvalidation")
distribution.grant_create_invalidation(lambda_fn)
```

Java:

```java
Distribution distribution;
Function lambdaFn;

distribution.grant(lambdaFn, "cloudfront:ListInvalidations", "cloudfront:GetInvalidation");
distribution.grantCreateInvalidation(lambdaFn);
```

C# / .NET:

```csharp
Distribution distribution;
Function lambdaFn;

distribution.Grant(lambdaFn, "cloudfront:ListInvalidations", "cloudfront:GetInvalidation");
distribution.GrantCreateInvalidation(lambdaFn);
```

Golang:

```go
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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/real-time-logs.html) in the CloudFront User Guide.

Example:

TypeScript:

```ts
// 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,
  },
});
```

Python:

```python
# 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
    )
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
    }
});
```

Golang:

```go
// 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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-using-grpc.html)
in the CloudFront User Guide.

Example:

TypeScript:

```ts
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,
  },
});
```

Python:

```python
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
    )
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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
    }
});
```

Golang:

```go
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](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-cloudfront.CfnDistribution.html) if you wish to avoid the deletion and recreation of your distribution.
To do this, use [escape hatches](https://docs.aws.amazon.com/cdk/v2/guide/cfn_layer.html) to override the logical ID created by the new Distribution construct with the logical ID created by the old construct.

Example:

TypeScript:

```ts
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');
```

Python:

```python
# 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")
```

Java:

```java
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");
```

C# / .NET:

```csharp
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");
```

Golang:

```go
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](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront_origins-readme.html) 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:

TypeScript:

```ts
declare const sourceBucket: s3.Bucket;
declare const oai: cloudfront.OriginAccessIdentity;

new cloudfront.CloudFrontWebDistribution(this, 'MyCfWebDistribution', {
  originConfigs: [
    {
      s3OriginSource: {
        s3BucketSource: sourceBucket,
        originAccessIdentity: oai,
      },
      behaviors : [ {isDefaultBehavior: true}],
    },
  ],
});
```

Python:

```python
# 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)]
    )
    ]
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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 } }
    } }
});
```

Golang:

```go
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:

TypeScript:

```ts
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
  },
});
```

Python:

```python
# source_bucket: s3.Bucket

distribution = cloudfront.Distribution(self, "MyCfWebDistribution",
    default_behavior=cloudfront.BehaviorOptions(
        origin=origins.S3Origin(source_bucket)
    )
)
```

Java:

```java
Bucket sourceBucket;

Distribution distribution = Distribution.Builder.create(this, "MyCfWebDistribution")
        .defaultBehavior(BehaviorOptions.builder()
                .origin(new S3Origin(sourceBucket))
                .build())
        .build();
```

C# / .NET:

```csharp
Bucket sourceBucket;

var distribution = new Distribution(this, "MyCfWebDistribution", new DistributionProps {
    DefaultBehavior = new BehaviorOptions {
        Origin = new S3Origin(sourceBucket)
    }
});
```

Golang:

```go
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.

TypeScript:

```ts
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' }]
    }
  ],
});
```

Python:

```python
# 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")]
    )
    ]
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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" } }
    } }
});
```

Golang:

```go
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:

TypeScript:

```ts
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'),
    }
  }
});
```

Python:

```python
# 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")
        )
    }
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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")
        } }
    }
});
```

Golang:

```go
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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ViewerCertificate.html) class should be passed in to the `domainNames` prop in the modern API.

TypeScript:

```ts
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,
});
```

Python:

```python
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
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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
});
```

Golang:

```go
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:

TypeScript:

```ts
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,
});
```

Python:

```python
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
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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
});
```

Golang:

```go
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](https://docs.aws.amazon.com/cdk/v2/guide/cfn_layer.html)

TypeScript:

```ts
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,
});
```

Python:

```python
# 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
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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
});
```

Golang:

```go
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:

TypeScript:

```ts
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');
```

Python:

```python
# 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")
```

Java:

```java
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");
```

C# / .NET:

```csharp
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");
```

Golang:

```go
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](https://docs.aws.amazon.com/cdk/v2/guide/cfn_layer.html) to override what the CDK synthesizes, if you can't change the properties directly.

## CloudFrontWebDistribution API

> The [`CloudFrontWebDistribution`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CloudFrontWebDistribution.html) construct is the original construct written for working with CloudFront distributions and has been marked as deprecated.
> Users are encouraged to use the newer [`Distribution`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.Distribution.html) instead, as it has a simpler interface and receives new features faster.

Example usage:

TypeScript:

```ts
// Using a CloudFrontWebDistribution construct.

declare const sourceBucket: s3.Bucket;
const distribution = new cloudfront.CloudFrontWebDistribution(this, 'MyDistribution', {
  originConfigs: [
    {
      s3OriginSource: {
        s3BucketSource: sourceBucket,
      },
      behaviors : [ {isDefaultBehavior: true}],
    },
  ],
});
```

Python:

```python
# 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)]
    )
    ]
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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 } }
    } }
});
```

Golang:

```go
// 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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-https-alternate-domain-names.html) 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:

TypeScript:

```ts
    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',
      ),
    });
```

Python:

```python
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")
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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")
});
```

Golang:

```go
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](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-certificatemanager-readme.html)
or [Importing Certificates into AWS Certificate Manager](https://docs.aws.amazon.com/acm/latest/userguide/import-certificate.html)
in the AWS Certificate Manager User Guide.

Example:

TypeScript:

```ts
    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
        },
      ),
    });
```

Python:

```python
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
    )
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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
    })
});
```

Golang:

```go
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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cnames-and-https-procedures.html#cnames-and-https-uploading-certificates) in the CloudFront User Guide.

Example:

TypeScript:

```ts
    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
        },
      ),
    });
```

Python:

```python
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
    )
)
```

Java:

```java
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();
```

C# / .NET:

```csharp
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
    })
});
```

Golang:

```go
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:

TypeScript:

```ts
// 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,
          ],
        },
      ],
    },
  ],
});
```

Python:

```python
# 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
            ]
        )
        ]
    )
    ]
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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 }
        } }
    } }
});
```

Golang:

```go
// 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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/georestrictions.html) in the CloudFront User Guide.

Example:

TypeScript:

```ts
// 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'),
});
```

Python:

```python
# 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")
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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")
});
```

Golang:

```go
// 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](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#origin-connection-attempts)

See [Origin Connection Timeout](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#origin-connection-timeout)

Example usage:

TypeScript:

```ts
// 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,
        },
      ],
    },
  ],
});
```

Python:

```python
# 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
        )
        ]
    )
    ]
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
        } }
    } }
});
```

Golang:

```go
// 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.

TypeScript:

```ts
// 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,
        },
      ],
    },
  ],
});
```

Python:

```python
# 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
        )
        ]
    )
    ]
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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
        } }
    } }
});
```

Golang:

```go
// 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`.

```bash
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`.

```bash
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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.PublicKey.html).

Example:

TypeScript:

```ts
// 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 ...',
});
```

Python:

```python
# Create a key group to use with CloudFront signed URLs and signed cookies.
cloudfront.KeyGroup(self, "MyKeyGroup",
    items=[
        cloudfront.PublicKey(self, "MyPublicKey",
            encoded_key="..."
        )
    ]
)
```

Java:

```java
// 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();
```

C# / .NET:

```csharp
// 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 = "..."
        }) }
});
```

Golang:

```go
// 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](https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_UpdatePublicKey.html). 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:

TypeScript:

```ts
// Step 1: Original deployment
const originalKey = new cloudfront.PublicKey(this, 'MyPublicKeyV1', {
  encodedKey: '...', // contents of original public_key.pem file
});
```

Python:

```python
# Step 1: Original deployment
original_key = cloudfront.PublicKey(self, "MyPublicKeyV1",
    encoded_key="..."
)
```

Java:

```java
// Step 1: Original deployment
PublicKey originalKey = PublicKey.Builder.create(this, "MyPublicKeyV1")
        .encodedKey("...")
        .build();
```

C# / .NET:

```csharp
// Step 1: Original deployment
var originalKey = new PublicKey(this, "MyPublicKeyV1", new PublicKeyProps {
    EncodedKey = "..."
});
```

Golang:

```go
// 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:

TypeScript:

```ts
// 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
});
```

Python:

```python
# Step 2: In a subsequent deployment, create a new key with a different ID
updated_key = cloudfront.PublicKey(self, "MyPublicKeyV2",
    encoded_key="..."
)
```

Java:

```java
// Step 2: In a subsequent deployment, create a new key with a different ID
PublicKey updatedKey = PublicKey.Builder.create(this, "MyPublicKeyV2")
        .encodedKey("...")
        .build();
```

C# / .NET:

```csharp
// Step 2: In a subsequent deployment, create a new key with a different ID
var updatedKey = new PublicKey(this, "MyPublicKeyV2", new PublicKeyProps {
    EncodedKey = "..."
});
```

Golang:

```go
// 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:

- <https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html>
- <https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html>

## Types

### Constructs (L2)

- [`CachePolicy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CachePolicy.html) Construct (L2) A Cache Policy configuration.
- [`CloudFrontWebDistribution`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CloudFrontWebDistribution.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.Distribution.html) Construct (L2) A CloudFront distribution with associated origin(s) and caching behavior(s).
- [`Function`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.Function.html) Construct (L2) A CloudFront Function.
- [`FunctionUrlOriginAccessControl`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.FunctionUrlOriginAccessControl.html) Construct (L2) An Origin Access Control for Lambda Function URLs.
- [`KeyGroup`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.KeyGroup.html) Construct (L2) A Key Group configuration.
- [`KeyValueStore`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.KeyValueStore.html) Construct (L2) A CloudFront Key Value Store.
- [`MediaPackageV2OriginAccessControl`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.MediaPackageV2OriginAccessControl.html) Construct (L2) An Origin Access Control for AWS Elemental MediaPackage V2 origins.
- [`OriginAccessIdentity`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginAccessIdentity.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginRequestPolicy.html) Construct (L2) A Origin Request Policy configuration.
- [`PublicKey`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.PublicKey.html) Construct (L2) A Public Key Configuration.
- [`RealtimeLogConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.RealtimeLogConfig.html) Construct (L2) A Realtime Log Config configuration.
- [`ResponseHeadersPolicy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ResponseHeadersPolicy.html) Construct (L2) A Response Headers Policy configuration.
- [`S3OriginAccessControl`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.S3OriginAccessControl.html) Construct (L2) An Origin Access Control for Amazon S3 origins.
- [`VpcOrigin`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.VpcOrigin.html) Construct (L2) A CloudFront VPC Origin configuration.

### Constructs (L1)

- [`CfnAnycastIpList`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnAnycastIpList.html) Construct (L1) An Anycast static IP list.
- [`CfnCachePolicy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnCachePolicy.html) Construct (L1) A cache policy.
- [`CfnCloudFrontOriginAccessIdentity`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnCloudFrontOriginAccessIdentity.html) Construct (L1) The request to create a new origin access identity (OAI).
- [`CfnConnectionFunction`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnConnectionFunction.html) Construct (L1) A connection function.
- [`CfnConnectionGroup`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnConnectionGroup.html) Construct (L1) The connection group for your distribution tenants.
- [`CfnContinuousDeploymentPolicy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnContinuousDeploymentPolicy.html) Construct (L1) Creates a continuous deployment policy that routes a subset of production traffic from a primary distribution to a staging distribution.
- [`CfnDistribution`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistributionTenant.html) Construct (L1) The distribution tenant.
- [`CfnFieldLevelEncryptionConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFieldLevelEncryptionConfig.html) Construct (L1) Resource Type definition for AWS::CloudFront::FieldLevelEncryptionConfig.
- [`CfnFieldLevelEncryptionProfile`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFieldLevelEncryptionProfile.html) Construct (L1) Resource Type definition for AWS::CloudFront::FieldLevelEncryptionProfile.
- [`CfnFunction`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFunction.html) Construct (L1) Creates a CloudFront function.
- [`CfnKeyGroup`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnKeyGroup.html) Construct (L1) A key group.
- [`CfnKeyValueStore`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnKeyValueStore.html) Construct (L1) The key value store.
- [`CfnMonitoringSubscription`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnMonitoringSubscription.html) Construct (L1) A monitoring subscription.
- [`CfnOriginAccessControl`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnOriginAccessControl.html) Construct (L1) Creates a new origin access control in CloudFront.
- [`CfnOriginRequestPolicy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnOriginRequestPolicy.html) Construct (L1) An origin request policy.
- [`CfnPublicKey`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnPublicKey.html) Construct (L1) A public key that you can use with [signed URLs and signed cookies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html) , or with [field-level encryption](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/field-level-encryption.html) .
- [`CfnRealtimeLogConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnRealtimeLogConfig.html) Construct (L1) A real-time log configuration.
- [`CfnResponseHeadersPolicy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.html) Construct (L1) A response headers policy.
- [`CfnStreamingDistribution`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnStreamingDistribution.html) Construct (L1) This resource is deprecated.
- [`CfnTrustStore`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnTrustStore.html) Construct (L1) A trust store.
- [`CfnVpcOrigin`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnVpcOrigin.html) Construct (L1) An Amazon CloudFront VPC origin.

### Enums

- [`AccessLevel`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.AccessLevel.html) Enum The level of permissions granted to the CloudFront Distribution when configuring OAC.
- [`CloudFrontAllowedCachedMethods`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CloudFrontAllowedCachedMethods.html) Enum Enums for the methods CloudFront can cache.
- [`CloudFrontAllowedMethods`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CloudFrontAllowedMethods.html) Enum An enum for the supported methods to a CloudFront distribution.
- [`FailoverStatusCode`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.FailoverStatusCode.html) Enum HTTP status code to failover to second origin.
- [`FunctionEventType`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.FunctionEventType.html) Enum The type of events that a CloudFront function can be invoked in response to.
- [`HeadersFrameOption`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.HeadersFrameOption.html) Enum Enum representing possible values of the X-Frame-Options HTTP response header.
- [`HeadersReferrerPolicy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.HeadersReferrerPolicy.html) Enum Enum representing possible values of the Referrer-Policy HTTP response header.
- [`HttpVersion`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.HttpVersion.html) Enum The HTTP version(s) to enable on the distribution.
- [`LambdaEdgeEventType`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.LambdaEdgeEventType.html) Enum The type of events that a Lambda@Edge function can be invoked in response to.
- [`OriginAccessControlOriginType`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginAccessControlOriginType.html) Enum Origin types supported by Origin Access Control.
- [`OriginIpAddressType`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginIpAddressType.html) Enum The IP address type for the origin.
- [`OriginProtocolPolicy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginProtocolPolicy.html) Enum Defines what protocols CloudFront will use to connect to an origin.
- [`OriginSelectionCriteria`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginSelectionCriteria.html) Enum The selection criteria for the origin group.
- [`OriginSslPolicy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginSslPolicy.html) Enum
- [`PriceClass`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.PriceClass.html) Enum The price class determines how many edge locations CloudFront will use for your distribution.
- [`SecurityPolicyProtocol`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.SecurityPolicyProtocol.html) Enum The minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections.
- [`SigningBehavior`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.SigningBehavior.html) Enum Options for which requests CloudFront signs.
- [`SigningProtocol`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.SigningProtocol.html) Enum The signing protocol of the Origin Access Control.
- [`SSLMethod`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.SSLMethod.html) Enum The SSL method CloudFront will use for your distribution.
- [`ViewerProtocolPolicy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ViewerProtocolPolicy.html) Enum How HTTPs should be handled with your distribution.

### Structs

- [`AddBehaviorOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.AddBehaviorOptions.html) Struct Options for adding a new behavior to a Distribution.
- [`Behavior`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.Behavior.html) Struct A CloudFront behavior wrapper.
- [`BehaviorOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.BehaviorOptions.html) Struct Options for creating a new behavior.
- [`CachePolicyProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CachePolicyProps.html) Struct Properties for creating a Cache Policy.
- [`CfnAnycastIpList.AnycastIpListProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnAnycastIpList.AnycastIpListProperty.html) Struct An Anycast static IP list.
- [`CfnAnycastIpList.IpamCidrConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnAnycastIpList.IpamCidrConfigProperty.html) Struct Configuration for an IPAM CIDR that defines a specific IP address range, IPAM pool, and associated Anycast IP address.
- [`CfnAnycastIpList.IpamCidrConfigResultProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnAnycastIpList.IpamCidrConfigResultProperty.html) Struct The result for the IPAM CIDR that defines a specific IP address range, IPAM pool, and associated Anycast IP address.
- [`CfnAnycastIpList.TagsProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnAnycastIpList.TagsProperty.html) Struct A complex type that contains zero or more `Tag` elements.
- [`CfnAnycastIpListProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnAnycastIpListProps.html) Struct Properties for defining a `CfnAnycastIpList`.
- [`CfnCachePolicy.CachePolicyConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnCachePolicy.CachePolicyConfigProperty.html) Struct A cache policy configuration.
- [`CfnCachePolicy.CookiesConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnCachePolicy.CookiesConfigProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnCachePolicy.HeadersConfigProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnCachePolicy.ParametersInCacheKeyAndForwardedToOriginProperty.html) Struct This object determines the values that CloudFront includes in the cache key.
- [`CfnCachePolicy.QueryStringsConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnCachePolicy.QueryStringsConfigProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnCachePolicyProps.html) Struct Properties for defining a `CfnCachePolicy`.
- [`CfnCloudFrontOriginAccessIdentity.CloudFrontOriginAccessIdentityConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnCloudFrontOriginAccessIdentity.CloudFrontOriginAccessIdentityConfigProperty.html) Struct Origin access identity configuration.
- [`CfnCloudFrontOriginAccessIdentityProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnCloudFrontOriginAccessIdentityProps.html) Struct Properties for defining a `CfnCloudFrontOriginAccessIdentity`.
- [`CfnConnectionFunction.ConnectionFunctionConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnConnectionFunction.ConnectionFunctionConfigProperty.html) Struct Contains configuration information about a CloudFront function.
- [`CfnConnectionFunction.KeyValueStoreAssociationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnConnectionFunction.KeyValueStoreAssociationProperty.html) Struct The key value store association.
- [`CfnConnectionFunctionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnConnectionFunctionProps.html) Struct Properties for defining a `CfnConnectionFunction`.
- [`CfnConnectionGroupProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnConnectionGroupProps.html) Struct Properties for defining a `CfnConnectionGroup`.
- [`CfnContinuousDeploymentPolicy.ContinuousDeploymentPolicyConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnContinuousDeploymentPolicy.ContinuousDeploymentPolicyConfigProperty.html) Struct Contains the configuration for a continuous deployment policy.
- [`CfnContinuousDeploymentPolicy.SessionStickinessConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnContinuousDeploymentPolicy.SessionStickinessConfigProperty.html) Struct Session stickiness provides the ability to define multiple requests from a single viewer as a single session.
- [`CfnContinuousDeploymentPolicy.SingleHeaderConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnContinuousDeploymentPolicy.SingleHeaderConfigProperty.html) Struct Determines which HTTP requests are sent to the staging distribution.
- [`CfnContinuousDeploymentPolicy.SingleHeaderPolicyConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnContinuousDeploymentPolicy.SingleHeaderPolicyConfigProperty.html) Struct Defines a single header policy for a CloudFront distribution.
- [`CfnContinuousDeploymentPolicy.SingleWeightConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnContinuousDeploymentPolicy.SingleWeightConfigProperty.html) Struct This configuration determines the percentage of HTTP requests that are sent to the staging distribution.
- [`CfnContinuousDeploymentPolicy.SingleWeightPolicyConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnContinuousDeploymentPolicy.SingleWeightPolicyConfigProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnContinuousDeploymentPolicy.TrafficConfigProperty.html) Struct The traffic configuration of your continuous deployment.
- [`CfnContinuousDeploymentPolicyProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnContinuousDeploymentPolicyProps.html) Struct Properties for defining a `CfnContinuousDeploymentPolicy`.
- [`CfnDistribution.CacheBehaviorProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.CacheBehaviorProperty.html) Struct A complex type that describes how CloudFront processes requests.
- [`CfnDistribution.CacheTagConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.CacheTagConfigProperty.html) Struct A complex type that specifies the HTTP header name from which CloudFront extracts cache tags from origin responses.
- [`CfnDistribution.ConnectionFunctionAssociationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.ConnectionFunctionAssociationProperty.html) Struct A connection function association.
- [`CfnDistribution.CookiesProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.CookiesProperty.html) Struct This field is deprecated.
- [`CfnDistribution.CustomErrorResponseProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.CustomErrorResponseProperty.html) Struct A complex type that controls:.
- [`CfnDistribution.CustomOriginConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.CustomOriginConfigProperty.html) Struct A custom origin.
- [`CfnDistribution.DefaultCacheBehaviorProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.DefaultCacheBehaviorProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.DefinitionProperty.html) Struct The value that you assigned to the parameter.
- [`CfnDistribution.DistributionConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.DistributionConfigProperty.html) Struct A distribution configuration.
- [`CfnDistribution.ForwardedValuesProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.ForwardedValuesProperty.html) Struct > This field only supports standard distributions.
- [`CfnDistribution.FunctionAssociationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.FunctionAssociationProperty.html) Struct A CloudFront function that is associated with a cache behavior in a CloudFront distribution.
- [`CfnDistribution.GeoRestrictionProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.GeoRestrictionProperty.html) Struct A complex type that controls the countries in which your content is distributed.
- [`CfnDistribution.GrpcConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.GrpcConfigProperty.html) Struct Amazon CloudFront supports gRPC, an open-source remote procedure call (RPC) framework built on HTTP/2.
- [`CfnDistribution.LambdaFunctionAssociationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.LambdaFunctionAssociationProperty.html) Struct A complex type that contains a Lambda@Edge function association.
- [`CfnDistribution.LegacyCustomOriginProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.LegacyCustomOriginProperty.html) Struct A custom origin.
- [`CfnDistribution.LegacyS3OriginProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.LegacyS3OriginProperty.html) Struct The origin as an Amazon S3 bucket.
- [`CfnDistribution.LoggingProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.LoggingProperty.html) Struct A complex type that specifies whether access logs are written for the distribution.
- [`CfnDistribution.OriginCustomHeaderProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.OriginCustomHeaderProperty.html) Struct A complex type that contains `HeaderName` and `HeaderValue` elements, if any, for this distribution.
- [`CfnDistribution.OriginGroupFailoverCriteriaProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.OriginGroupFailoverCriteriaProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.OriginGroupMemberProperty.html) Struct An origin in an origin group.
- [`CfnDistribution.OriginGroupMembersProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.OriginGroupMembersProperty.html) Struct A complex data type for the origins included in an origin group.
- [`CfnDistribution.OriginGroupProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.OriginGroupProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.OriginGroupsProperty.html) Struct A complex data type for the origin groups specified for a distribution.
- [`CfnDistribution.OriginMtlsConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.OriginMtlsConfigProperty.html) Struct Configures mutual TLS authentication between CloudFront and your origin server.
- [`CfnDistribution.OriginProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.OriginProperty.html) Struct An origin.
- [`CfnDistribution.OriginShieldProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.OriginShieldProperty.html) Struct CloudFront Origin Shield.
- [`CfnDistribution.ParameterDefinitionProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.ParameterDefinitionProperty.html) Struct A list of parameter values to add to the resource.
- [`CfnDistribution.RestrictionsProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.RestrictionsProperty.html) Struct A complex type that identifies ways in which you want to restrict distribution of your content.
- [`CfnDistribution.S3OriginConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.S3OriginConfigProperty.html) Struct A complex type that contains information about the Amazon S3 origin.
- [`CfnDistribution.StatusCodesProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.StatusCodesProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.StringSchemaProperty.html) Struct
- [`CfnDistribution.TenantConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.TenantConfigProperty.html) Struct > This field only supports multi-tenant distributions.
- [`CfnDistribution.TrustStoreConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.TrustStoreConfigProperty.html) Struct A trust store configuration.
- [`CfnDistribution.ViewerCertificateProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.ViewerCertificateProperty.html) Struct A complex type that determines the distribution's SSL/TLS configuration for communicating with viewers.
- [`CfnDistribution.ViewerMtlsConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.ViewerMtlsConfigProperty.html) Struct A viewer mTLS configuration.
- [`CfnDistribution.VpcOriginConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistribution.VpcOriginConfigProperty.html) Struct An Amazon CloudFront VPC origin configuration.
- [`CfnDistributionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistributionProps.html) Struct Properties for defining a `CfnDistribution`.
- [`CfnDistributionTenant.CertificateProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistributionTenant.CertificateProperty.html) Struct The Certificate Manager (ACM) certificate associated with your distribution.
- [`CfnDistributionTenant.CustomizationsProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistributionTenant.CustomizationsProperty.html) Struct Customizations for the distribution tenant.
- [`CfnDistributionTenant.DomainResultProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistributionTenant.DomainResultProperty.html) Struct The details about the domain result.
- [`CfnDistributionTenant.GeoRestrictionCustomizationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistributionTenant.GeoRestrictionCustomizationProperty.html) Struct The customizations that you specified for the distribution tenant for geographic restrictions.
- [`CfnDistributionTenant.ManagedCertificateRequestProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistributionTenant.ManagedCertificateRequestProperty.html) Struct An object that represents the request for the Amazon CloudFront managed ACM certificate.
- [`CfnDistributionTenant.ParameterProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistributionTenant.ParameterProperty.html) Struct A list of parameter values to add to the resource.
- [`CfnDistributionTenant.WebAclCustomizationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistributionTenant.WebAclCustomizationProperty.html) Struct The AWS WAF web ACL customization specified for the distribution tenant.
- [`CfnDistributionTenantProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnDistributionTenantProps.html) Struct Properties for defining a `CfnDistributionTenant`.
- [`CfnFieldLevelEncryptionConfig.ContentTypeProfileConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFieldLevelEncryptionConfig.ContentTypeProfileConfigProperty.html) Struct How CloudFront handles content types, including the profile paired with each one.
- [`CfnFieldLevelEncryptionConfig.ContentTypeProfileProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFieldLevelEncryptionConfig.ContentTypeProfileProperty.html) Struct A content type paired with the field-level encryption profile that encrypts it.
- [`CfnFieldLevelEncryptionConfig.QueryArgProfileConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFieldLevelEncryptionConfig.QueryArgProfileConfigProperty.html) Struct How CloudFront handles query arguments, including the profile paired with each one.
- [`CfnFieldLevelEncryptionConfig.QueryArgProfileProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFieldLevelEncryptionConfig.QueryArgProfileProperty.html) Struct A query argument paired with the field-level encryption profile that encrypts it.
- [`CfnFieldLevelEncryptionConfigProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFieldLevelEncryptionConfigProps.html) Struct Properties for defining a `CfnFieldLevelEncryptionConfig`.
- [`CfnFieldLevelEncryptionProfile.EncryptionEntityProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFieldLevelEncryptionProfile.EncryptionEntityProperty.html) Struct A public key, its provider identity, and the field patterns CloudFront encrypts with that key.
- [`CfnFieldLevelEncryptionProfile.FieldLevelEncryptionProfileConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFieldLevelEncryptionProfile.FieldLevelEncryptionProfileConfigProperty.html) Struct The configuration of a field-level encryption profile.
- [`CfnFieldLevelEncryptionProfileProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFieldLevelEncryptionProfileProps.html) Struct Properties for defining a `CfnFieldLevelEncryptionProfile`.
- [`CfnFunction.FunctionConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFunction.FunctionConfigProperty.html) Struct Contains configuration information about a CloudFront function.
- [`CfnFunction.FunctionMetadataProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFunction.FunctionMetadataProperty.html) Struct Contains metadata about a CloudFront function.
- [`CfnFunction.KeyValueStoreAssociationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFunction.KeyValueStoreAssociationProperty.html) Struct The key value store association.
- [`CfnFunctionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnFunctionProps.html) Struct Properties for defining a `CfnFunction`.
- [`CfnKeyGroup.KeyGroupConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnKeyGroup.KeyGroupConfigProperty.html) Struct A key group configuration.
- [`CfnKeyGroupProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnKeyGroupProps.html) Struct Properties for defining a `CfnKeyGroup`.
- [`CfnKeyValueStore.ImportSourceProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnKeyValueStore.ImportSourceProperty.html) Struct The import source for the key value store.
- [`CfnKeyValueStoreProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnKeyValueStoreProps.html) Struct Properties for defining a `CfnKeyValueStore`.
- [`CfnMonitoringSubscription.MonitoringSubscriptionProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnMonitoringSubscription.MonitoringSubscriptionProperty.html) Struct A monitoring subscription.
- [`CfnMonitoringSubscription.RealtimeMetricsSubscriptionConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnMonitoringSubscription.RealtimeMetricsSubscriptionConfigProperty.html) Struct A subscription configuration for additional CloudWatch metrics.
- [`CfnMonitoringSubscriptionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnMonitoringSubscriptionProps.html) Struct Properties for defining a `CfnMonitoringSubscription`.
- [`CfnOriginAccessControl.OriginAccessControlConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnOriginAccessControl.OriginAccessControlConfigProperty.html) Struct Creates a new origin access control in CloudFront.
- [`CfnOriginAccessControlProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnOriginAccessControlProps.html) Struct Properties for defining a `CfnOriginAccessControl`.
- [`CfnOriginRequestPolicy.CookiesConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnOriginRequestPolicy.CookiesConfigProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnOriginRequestPolicy.HeadersConfigProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnOriginRequestPolicy.OriginRequestPolicyConfigProperty.html) Struct An origin request policy configuration.
- [`CfnOriginRequestPolicy.QueryStringsConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnOriginRequestPolicy.QueryStringsConfigProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnOriginRequestPolicyProps.html) Struct Properties for defining a `CfnOriginRequestPolicy`.
- [`CfnPublicKey.PublicKeyConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnPublicKey.PublicKeyConfigProperty.html) Struct Configuration information about a public key that you can use with [signed URLs and signed cookies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html) , or with [field-level encryption](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/field-level-encryption.html) .
- [`CfnPublicKeyProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnPublicKeyProps.html) Struct Properties for defining a `CfnPublicKey`.
- [`CfnRealtimeLogConfig.EndPointProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnRealtimeLogConfig.EndPointProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnRealtimeLogConfig.KinesisStreamConfigProperty.html) Struct Contains information about the Amazon Kinesis data stream where you are sending real-time log data.
- [`CfnRealtimeLogConfigProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnRealtimeLogConfigProps.html) Struct Properties for defining a `CfnRealtimeLogConfig`.
- [`CfnResponseHeadersPolicy.AccessControlAllowHeadersProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.AccessControlAllowHeadersProperty.html) Struct A list of HTTP header names that CloudFront includes as values for the `Access-Control-Allow-Headers` HTTP response header.
- [`CfnResponseHeadersPolicy.AccessControlAllowMethodsProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.AccessControlAllowMethodsProperty.html) Struct A list of HTTP methods that CloudFront includes as values for the `Access-Control-Allow-Methods` HTTP response header.
- [`CfnResponseHeadersPolicy.AccessControlAllowOriginsProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.AccessControlAllowOriginsProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.AccessControlExposeHeadersProperty.html) Struct A list of HTTP headers that CloudFront includes as values for the `Access-Control-Expose-Headers` HTTP response header.
- [`CfnResponseHeadersPolicy.ContentSecurityPolicyProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.ContentSecurityPolicyProperty.html) Struct The policy directives and their values that CloudFront includes as values for the `Content-Security-Policy` HTTP response header.
- [`CfnResponseHeadersPolicy.ContentTypeOptionsProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.ContentTypeOptionsProperty.html) Struct Determines whether CloudFront includes the `X-Content-Type-Options` HTTP response header with its value set to `nosniff` .
- [`CfnResponseHeadersPolicy.CorsConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.CorsConfigProperty.html) Struct A configuration for a set of HTTP response headers that are used for cross-origin resource sharing (CORS).
- [`CfnResponseHeadersPolicy.CustomHeaderProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.CustomHeaderProperty.html) Struct An HTTP response header name and its value.
- [`CfnResponseHeadersPolicy.CustomHeadersConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.CustomHeadersConfigProperty.html) Struct A list of HTTP response header names and their values.
- [`CfnResponseHeadersPolicy.FrameOptionsProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.FrameOptionsProperty.html) Struct Determines whether CloudFront includes the `X-Frame-Options` HTTP response header and the header's value.
- [`CfnResponseHeadersPolicy.ReferrerPolicyProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.ReferrerPolicyProperty.html) Struct Determines whether CloudFront includes the `Referrer-Policy` HTTP response header and the header's value.
- [`CfnResponseHeadersPolicy.RemoveHeaderProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.RemoveHeaderProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.RemoveHeadersConfigProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.ResponseHeadersPolicyConfigProperty.html) Struct A response headers policy configuration.
- [`CfnResponseHeadersPolicy.SecurityHeadersConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.SecurityHeadersConfigProperty.html) Struct A configuration for a set of security-related HTTP response headers.
- [`CfnResponseHeadersPolicy.ServerTimingHeadersConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.ServerTimingHeadersConfigProperty.html) Struct A configuration for enabling the `Server-Timing` header in HTTP responses sent from CloudFront.
- [`CfnResponseHeadersPolicy.StrictTransportSecurityProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.StrictTransportSecurityProperty.html) Struct Determines whether CloudFront includes the `Strict-Transport-Security` HTTP response header and the header's value.
- [`CfnResponseHeadersPolicy.XSSProtectionProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicy.XSSProtectionProperty.html) Struct Determines whether CloudFront includes the `X-XSS-Protection` HTTP response header and the header's value.
- [`CfnResponseHeadersPolicyProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnResponseHeadersPolicyProps.html) Struct Properties for defining a `CfnResponseHeadersPolicy`.
- [`CfnStreamingDistribution.LoggingProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnStreamingDistribution.LoggingProperty.html) Struct A complex type that controls whether access logs are written for the streaming distribution.
- [`CfnStreamingDistribution.S3OriginProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnStreamingDistribution.S3OriginProperty.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnStreamingDistribution.StreamingDistributionConfigProperty.html) Struct The RTMP distribution's configuration information.
- [`CfnStreamingDistribution.TrustedSignersProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnStreamingDistribution.TrustedSignersProperty.html) Struct A list of AWS accounts whose public keys CloudFront can use to verify the signatures of signed URLs and signed cookies.
- [`CfnStreamingDistributionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnStreamingDistributionProps.html) Struct Properties for defining a `CfnStreamingDistribution`.
- [`CfnTrustStore.CaCertificatesBundleS3LocationProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnTrustStore.CaCertificatesBundleS3LocationProperty.html) Struct The CA certificates bundle location in Amazon S3.
- [`CfnTrustStore.CaCertificatesBundleSourceProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnTrustStore.CaCertificatesBundleSourceProperty.html) Struct A CA certificates bundle source.
- [`CfnTrustStoreProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnTrustStoreProps.html) Struct Properties for defining a `CfnTrustStore`.
- [`CfnVpcOrigin.VpcOriginEndpointConfigProperty`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnVpcOrigin.VpcOriginEndpointConfigProperty.html) Struct An Amazon CloudFront VPC origin endpoint configuration.
- [`CfnVpcOriginProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CfnVpcOriginProps.html) Struct Properties for defining a `CfnVpcOrigin`.
- [`CloudFrontWebDistributionAttributes`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CloudFrontWebDistributionAttributes.html) Struct Attributes used to import a Distribution.
- [`CloudFrontWebDistributionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CloudFrontWebDistributionProps.html) Struct
- [`CustomOriginConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CustomOriginConfig.html) Struct A custom origin configuration.
- [`DistributionAttributes`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.DistributionAttributes.html) Struct Attributes used to import a Distribution.
- [`DistributionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.DistributionProps.html) Struct Properties for a Distribution.
- [`EdgeLambda`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.EdgeLambda.html) Struct Represents a Lambda function version and event type when using Lambda@Edge.
- [`ErrorResponse`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ErrorResponse.html) Struct Options for configuring custom error responses.
- [`FileCodeOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.FileCodeOptions.html) Struct Options when reading the function's code from an external file.
- [`FunctionAssociation`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.FunctionAssociation.html) Struct Represents a CloudFront function and event type when using CF Functions.
- [`FunctionAttributes`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.FunctionAttributes.html) Struct Attributes of an existing CloudFront Function to import it.
- [`FunctionProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.FunctionProps.html) Struct Properties for creating a CloudFront Function.
- [`FunctionUrlOriginAccessControlProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.FunctionUrlOriginAccessControlProps.html) Struct Properties for creating a Lambda Function URL Origin Access Control resource.
- [`KeyGroupProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.KeyGroupProps.html) Struct Properties for creating a Public Key.
- [`KeyValueStoreProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.KeyValueStoreProps.html) Struct The properties to create a Key Value Store.
- [`LambdaFunctionAssociation`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.LambdaFunctionAssociation.html) Struct
- [`LoggingConfiguration`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.LoggingConfiguration.html) Struct Logging configuration for incoming requests.
- [`MediaPackageV2OriginAccessControlProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.MediaPackageV2OriginAccessControlProps.html) Struct Properties for creating a MediaPackage V2 Origin Access Control resource.
- [`OriginAccessControlBaseProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginAccessControlBaseProps.html) Struct Common properties for creating a Origin Access Control resource.
- [`OriginAccessIdentityProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginAccessIdentityProps.html) Struct Properties of CloudFront OriginAccessIdentity.
- [`OriginBindConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginBindConfig.html) Struct The struct returned from `IOrigin.bind`.
- [`OriginBindOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginBindOptions.html) Struct Options passed to Origin.bind().
- [`OriginFailoverConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginFailoverConfig.html) Struct The failover configuration used for Origin Groups, returned in `OriginBindConfig.failoverConfig`.
- [`OriginOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginOptions.html) Struct Options to define an Origin.
- [`OriginProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginProps.html) Struct Properties to define an Origin.
- [`OriginRequestPolicyProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginRequestPolicyProps.html) Struct Properties for creating a Origin Request Policy.
- [`PublicKeyProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.PublicKeyProps.html) Struct Properties for creating a Public Key.
- [`RealtimeLogConfigProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.RealtimeLogConfigProps.html) Struct Properties for defining a RealtimeLogConfig resource.
- [`ResponseCustomHeader`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ResponseCustomHeader.html) Struct An HTTP response header name and its value.
- [`ResponseCustomHeadersBehavior`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ResponseCustomHeadersBehavior.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ResponseHeadersContentSecurityPolicy.html) Struct The policy directives and their values that CloudFront includes as values for the Content-Security-Policy HTTP response header.
- [`ResponseHeadersContentTypeOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ResponseHeadersContentTypeOptions.html) Struct Determines whether CloudFront includes the X-Content-Type-Options HTTP response header with its value set to nosniff.
- [`ResponseHeadersCorsBehavior`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ResponseHeadersCorsBehavior.html) Struct Configuration for a set of HTTP response headers that are used for cross-origin resource sharing (CORS).
- [`ResponseHeadersFrameOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ResponseHeadersFrameOptions.html) Struct Determines whether CloudFront includes the X-Frame-Options HTTP response header and the header’s value.
- [`ResponseHeadersPolicyProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ResponseHeadersPolicyProps.html) Struct Properties for creating a Response Headers Policy.
- [`ResponseHeadersReferrerPolicy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ResponseHeadersReferrerPolicy.html) Struct Determines whether CloudFront includes the Referrer-Policy HTTP response header and the header’s value.
- [`ResponseHeadersStrictTransportSecurity`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ResponseHeadersStrictTransportSecurity.html) Struct Determines whether CloudFront includes the Strict-Transport-Security HTTP response header and the header’s value.
- [`ResponseHeadersXSSProtection`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ResponseHeadersXSSProtection.html) Struct Determines whether CloudFront includes the X-XSS-Protection HTTP response header and the header’s value.
- [`ResponseSecurityHeadersBehavior`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ResponseSecurityHeadersBehavior.html) Struct Configuration for a set of security-related HTTP response headers.
- [`S3OriginAccessControlProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.S3OriginAccessControlProps.html) Struct Properties for creating a S3 Origin Access Control resource.
- [`S3OriginConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.S3OriginConfig.html) Struct S3 origin configuration for CloudFront.
- [`SourceConfiguration`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.SourceConfiguration.html) Struct A source configuration is a wrapper for CloudFront origins and behaviors.
- [`ViewerCertificateOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ViewerCertificateOptions.html) Struct
- [`VpcOriginAttributes`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.VpcOriginAttributes.html) Struct The properties to import from the VPC origin.
- [`VpcOriginOptions`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.VpcOriginOptions.html) Struct VPC origin endpoint configuration.
- [`VpcOriginProps`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.VpcOriginProps.html) Struct VPC origin endpoint configuration.

### Classes

- [`AllowedMethods`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.AllowedMethods.html) Class The HTTP methods that the Behavior will accept requests on.
- [`AssetImportSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.AssetImportSource.html) Class An import source from a local file.
- [`CacheCookieBehavior`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CacheCookieBehavior.html) 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`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CachedMethods.html) Class The HTTP methods that the Behavior will cache requests on.
- [`CacheHeaderBehavior`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CacheHeaderBehavior.html) Class Determines whether any HTTP headers are included in the cache key and automatically included in requests that CloudFront sends to the origin.
- [`CacheQueryStringBehavior`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.CacheQueryStringBehavior.html) 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.
- [`Endpoint`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.Endpoint.html) Class Represents the endpoints available for targetting within a realtime log config resource.
- [`FunctionCode`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.FunctionCode.html) Class Represents the function's source code.
- [`FunctionRuntime`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.FunctionRuntime.html) Class The function's runtime environment version.
- [`GeoRestriction`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.GeoRestriction.html) Class Controls the countries in which content is distributed.
- [`ImportSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ImportSource.html) Class The data to be imported to the key value store.
- [`InlineImportSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.InlineImportSource.html) Class An import source from an inline string.
- [`OriginBase`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginBase.html) 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.
- [`OriginRequestCookieBehavior`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginRequestCookieBehavior.html) Class Determines whether any cookies in viewer requests (and if so, which cookies) are included in requests that CloudFront sends to the origin.
- [`OriginRequestHeaderBehavior`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginRequestHeaderBehavior.html) Class Determines whether any HTTP headers (and if so, which headers) are included in requests that CloudFront sends to the origin.
- [`OriginRequestQueryStringBehavior`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.OriginRequestQueryStringBehavior.html) 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.
- [`S3ImportSource`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.S3ImportSource.html) Class An import source from an S3 object.
- [`Signing`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.Signing.html) Class Options for how CloudFront signs requests.
- [`ViewerCertificate`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ViewerCertificate.html) Class Viewer certificate configuration class.
- [`VpcOriginEndpoint`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.VpcOriginEndpoint.html) Class Represents the VPC origin endpoint.

### Facades

- [`DistributionGrants`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.DistributionGrants.html) Facade Collection of grant methods for a IDistributionRef.

### Interfaces

- [`ICachePolicy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.ICachePolicy.html) Interface Represents a Cache Policy.
- [`IDistribution`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.IDistribution.html) Interface Interface for CloudFront distributions.
- [`IFunction`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.IFunction.html) Interface Represents a CloudFront Function.
- [`IKeyGroup`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.IKeyGroup.html) Interface Represents a Key Group.
- [`IKeyValueStore`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.IKeyValueStore.html) Interface A CloudFront Key Value Store.
- [`IOrigin`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.IOrigin.html) Interface Represents the concept of a CloudFront Origin.
- [`IOriginAccessControl`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.IOriginAccessControl.html) Interface Represents a CloudFront Origin Access Control.
- [`IOriginAccessIdentity`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.IOriginAccessIdentity.html) Interface Interface for CloudFront OriginAccessIdentity.
- [`IOriginRequestPolicy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.IOriginRequestPolicy.html) Interface Represents a Origin Request Policy.
- [`IPublicKey`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.IPublicKey.html) Interface Represents a Public Key.
- [`IRealtimeLogConfig`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.IRealtimeLogConfig.html) Interface Represents Realtime Log Configuration.
- [`IResponseHeadersPolicy`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.IResponseHeadersPolicy.html) Interface Represents a response headers policy.
- [`IVpcOrigin`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront.IVpcOrigin.html) Interface Represents a VPC origin.
