Skip to content
v2.274.0

CloudFrontWebDistribution L2 construct ​

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.

CloudFront fronts user provided content and caches it at edge locations across the world.

Here's how you can use this construct:

ts
const sourceBucket = new s3.Bucket(this, 'Bucket');

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

This will create a CloudFront distribution that uses your S3Bucket as its origin.

You can customize the distribution using additional properties from the CloudFrontWebDistributionProps interface.

Example ​

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
# 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
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();
csharp
// Install: dotnet add package Amazon.CDK.Lib
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
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
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,
})

Initializer ​

ts
new CloudFrontWebDistribution(scope: Construct, id: string, props: CloudFrontWebDistributionProps)
python
CloudFrontWebDistribution(scope: Construct, id: str, props: CloudFrontWebDistributionProps)
java
new CloudFrontWebDistribution(Construct scope, String id, CloudFrontWebDistributionProps props)
csharp
new CloudFrontWebDistribution(Construct scope, string id, CloudFrontWebDistributionProps props)
go
NewCloudFrontWebDistribution(Scope Construct, Id *string, Props CloudFrontWebDistributionProps)

Construct Props ​

commentoptionalstringcommentoptionalstrcommentoptionalStringCommentoptionalstringCommentoptional*string#
A comment for this distribution in the CloudFront console.

Default: No comment is added to distribution.

defaultRootObjectoptionalstringdefault_root_objectoptionalstrdefaultRootObjectoptionalStringDefaultRootObjectoptionalstringDefaultRootObjectoptional*string#
The default object to serve.

Default: "index.html" is served.

enabledoptionalbooleanenabledoptionalboolenabledoptionalBooleanEnabledoptionalboolEnabledoptional*bool= true#
Enable or disable the distribution.
enableIpV6optionalbooleanenable_ip_v6optionalboolenableIpV6optionalBooleanEnableIpV6optionalboolEnableIpV6optional*bool= true#
If your distribution should have IPv6 enabled.
errorConfigurationsoptionalCfnDistribution.CustomErrorResponseProperty[]error_configurationsoptionaltyping.List[CustomErrorResponseProperty]errorConfigurationsoptionalList<CustomErrorResponseProperty>ErrorConfigurationsoptionalCustomErrorResponseProperty[]ErrorConfigurationsoptional*[]CustomErrorResponseProperty#
How CloudFront should handle requests that are not successful (eg PageNotFound).

Default: No custom error configuration.

By default, CloudFront does not replace HTTP status codes in the 4xx and 5xx range with custom error messages. CloudFront does not cache HTTP status codes.

geoRestrictionoptionalGeoRestrictiongeo_restrictionoptionalGeoRestrictiongeoRestrictionoptionalGeoRestrictionGeoRestrictionoptionalGeoRestrictionGeoRestrictionoptionalGeoRestriction#
Controls the countries in which your content is distributed.

Default: No geo restriction

httpVersionoptionalHttpVersionhttp_versionoptionalHttpVersionhttpVersionoptionalHttpVersionHttpVersionoptionalHttpVersionHttpVersionoptionalHttpVersion= HttpVersion.HTTP2#
The HTTP version(s) to enable for viewers communicating with CloudFront.
loggingConfigoptionalLoggingConfigurationlogging_configoptionalLoggingConfigurationloggingConfigoptionalLoggingConfigurationLoggingConfigoptionalLoggingConfigurationLoggingConfigoptionalLoggingConfiguration#
Optional - if we should enable logging.

Default: no logging is enabled by default.

You can pass an empty object ({}) to have us auto create a bucket for logging. Omission of this property indicates no logging is to be enabled.

originConfigsSourceConfiguration[]origin_configstyping.List[SourceConfiguration]originConfigsList<SourceConfiguration>OriginConfigsSourceConfiguration[]OriginConfigs*[]SourceConfigurationrequired#
The origin configurations for this distribution.

Behaviors are a part of the origin.

priceClassoptionalPriceClassprice_classoptionalPriceClasspriceClassoptionalPriceClassPriceClassoptionalPriceClassPriceClassoptionalPriceClass#
The price class for the distribution (this impacts how many locations CloudFront uses for your distribution, and billing).

Default: PriceClass.PRICE_CLASS_100 the cheapest option for CloudFront is picked by default.

viewerCertificateoptionalViewerCertificateviewer_certificateoptionalViewerCertificateviewerCertificateoptionalViewerCertificateViewerCertificateoptionalViewerCertificateViewerCertificateoptionalViewerCertificate#
Specifies whether you want viewers to use HTTP or HTTPS to request your objects, whether you're using an alternate domain name with HTTPS, and if so, if you're using AWS Certificate Manager (ACM) or a third-party certificate authority.

Default: ViewerCertificate.fromCloudFrontDefaultCertificate()

viewerProtocolPolicyoptionalViewerProtocolPolicyviewer_protocol_policyoptionalViewerProtocolPolicyviewerProtocolPolicyoptionalViewerProtocolPolicyViewerProtocolPolicyoptionalViewerProtocolPolicyViewerProtocolPolicyoptionalViewerProtocolPolicy= RedirectToHTTPs#
The default viewer policy for incoming clients.
webACLIdoptionalstringweb_acl_idoptionalstrwebACLIdoptionalStringWebACLIdoptionalstringWebACLIdoptional*string#
Unique identifier that specifies the AWS WAF web ACL to associate with this CloudFront distribution.

Default: No AWS Web Application Firewall web access control list (web ACL).

notes

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.

To specify a web ACL created using AWS WAF Classic, use the ACL ID, for example 473e64fd-f30b-4765-81a0-62ad96dd167a.

Properties ​

distributionArnstringdistribution_arnstrdistributionArnStringDistributionArnstringDistributionArn*stringrequired#
The distribution ARN for this distribution.
distributionDomainNamestringdistribution_domain_namestrdistributionDomainNameStringDistributionDomainNamestringDistributionDomainName*stringrequired#
The domain name created by CloudFront for this distribution.

If you are using aliases for your distribution, this is the domainName your DNS records should point to. (In Route53, you could create an ALIAS record to this value, for example.)

distributionIdstringdistribution_idstrdistributionIdStringDistributionIdstringDistributionId*stringrequired#
The distribution ID for this distribution.
distributionRefDistributionReferencedistribution_refDistributionReferencedistributionRefDistributionReferenceDistributionRefDistributionReferenceDistributionRefDistributionReferencerequired#
A reference to a Distribution resource.
The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

Collection of grant methods for a Distribution.
loggingBucketmay be undefinedIBucketlogging_bucketmay be undefinedIBucketloggingBucketmay be undefinedIBucketLoggingBucketmay be undefinedIBucketLoggingBucketmay be undefinedIBucket#
The logging bucket for this CloudFront distribution.

If logging is not enabled for this distribution - this property will be undefined.

nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.

Methods ​

applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

fromDistributionAttributes(scope: Construct, id: string, attrs: CloudFrontWebDistributionAttributes): IDistribution@staticmethod def from_distribution_attributes(scope: Construct, id: str, attrs: CloudFrontWebDistributionAttributes) -> IDistributionpublic static IDistribution fromDistributionAttributes(Construct scope, String id, CloudFrontWebDistributionAttributes attrs)public static IDistribution FromDistributionAttributes(Construct scope, string id, CloudFrontWebDistributionAttributes attrs)func FromDistributionAttributes(Scope Construct, Id *string, Attrs CloudFrontWebDistributionAttributes) IDistributionstatic#
Creates a construct that represents an external (imported) distribution.
grant(identity: IGrantable, ...actions: string[]): Grantdef grant(self, identity: IGrantable, actions: str) -> Grantpublic Grant grant(IGrantable identity, String actions)public Grant Grant(IGrantable identity, string actions)func Grant(Identity IGrantable, Actions *string) Grant#
Adds an IAM policy statement associated with this distribution to an IAM principal's policy.

[disable-awslint:no-grants]

2 parameters

Parameters

  • identityidentityidentityidentityIdentity — The principal.
  • actionsactionsactionsactionsActions — The set of actions to allow (i.e. "cloudfront:ListInvalidations").
grantCreateInvalidation(identity: IGrantable): Grantdef grant_create_invalidation(self, identity: IGrantable) -> Grantpublic Grant grantCreateInvalidation(IGrantable identity)public Grant GrantCreateInvalidation(IGrantable identity)func GrantCreateInvalidation(Identity IGrantable) Grant#
Grant to create invalidations for this bucket to an IAM principal (Role/Group/User).

[disable-awslint:no-grants]

1 parameter

Parameters

  • identityidentityidentityidentityIdentity — The principal.
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.