Package software.amazon.awscdk.services.cloudfront
Amazon CloudFront Construct Library
Amazon CloudFront is a web service that speeds up distribution of your static and dynamic web content, such as .html, .css, .js, and image files, to your users. CloudFront delivers your content through a worldwide network of data centers called edge locations. When a user requests content that you're serving with CloudFront, the user is routed to the edge location that provides the lowest latency, so that content is delivered with the best possible performance.
Distribution API
The Distribution
API is currently being built to replace the existing CloudFrontWebDistribution
API. The Distribution
API is optimized for the
most common use cases of CloudFront distributions (e.g., single origin and behavior, few customizations) while still providing the ability for more
advanced use cases. The API focuses on simplicity for the common use cases, and convenience methods for creating the behaviors and origins necessary
for more complex use cases.
Creating a distribution
CloudFront distributions deliver your content from one or more origins; an origin is the location where you store the original version of your
content. Origins can be created from S3 buckets or a custom origin (HTTP server). Constructs to define origins are in the aws-cdk-lib/aws-cloudfront-origins
module.
Each distribution has a default behavior which applies to all requests to that distribution, and routes requests to a primary origin. Additional behaviors may be specified for an origin with a given URL path pattern. Behaviors allow routing with multiple origins, controlling which HTTP methods to support, whether to require users to use HTTPS, and what query strings or cookies to forward to your origin, among other settings.
From an S3 Bucket
An S3 bucket can be added as an origin. If the bucket is configured as a website endpoint, the distribution can use S3 redirects and S3 custom error documents.
// Creates a distribution from an S3 bucket. Bucket myBucket = new Bucket(this, "myBucket"); Distribution.Builder.create(this, "myDist") .defaultBehavior(BehaviorOptions.builder().origin(new S3Origin(myBucket)).build()) .build();
The above will treat the bucket differently based on if IBucket.isWebsite
is set or not. If the bucket is configured as a website, the bucket is
treated as an HTTP origin, and the built-in S3 redirects and error pages can be used. Otherwise, the bucket is handled as a bucket origin and
CloudFront's redirect and error handling will be used. In the latter case, the Origin will create an origin access identity and grant it access to the
underlying bucket. This can be used in conjunction with a bucket that is not public to require that your users access your content using CloudFront
URLs and not S3 URLs directly.
ELBv2 Load Balancer
An Elastic Load Balancing (ELB) v2 load balancer may be used as an origin. In order for a load balancer to serve as an origin, it must be publicly
accessible (internetFacing
is true). Both Application and Network load balancers are supported.
// Creates a distribution from an ELBv2 load balancer 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();
From an HTTP endpoint
Origins can also be created from any other HTTP endpoint, given the domain name, and optionally, other origin properties.
// Creates a distribution from an HTTP endpoint // Creates a distribution from an HTTP endpoint Distribution.Builder.create(this, "myDist") .defaultBehavior(BehaviorOptions.builder().origin(new HttpOrigin("www.example.com")).build()) .build();
Domain Names and Certificates
When you create a distribution, CloudFront assigns a domain name for the distribution, for example: d111111abcdef8.cloudfront.net
; this value can
be retrieved from distribution.distributionDomainName
. CloudFront distributions use a default certificate (*.cloudfront.net
) to support HTTPS by
default. If you want to use your own domain name, such as www.example.com
, you must associate a certificate with your distribution that contains
your domain name, and provide one (or more) domain names from the certificate for the distribution.
The certificate must be present in the AWS Certificate Manager (ACM) service in the US East (N. Virginia) region; the certificate
may either be created by ACM, or created elsewhere and imported into ACM. When a certificate is used, the distribution will support HTTPS connections
from SNI only and a minimum protocol version of TLSv1.2_2021 if the @aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021
feature flag is set, and TLSv1.2_2019 otherwise.
// To use your own domain name in a Distribution, you must associate a certificate import 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();
However, you can customize the minimum protocol version for the certificate while creating the distribution using minimumProtocolVersion
property.
// Create a Distribution with a custom domain name and a minimum protocol version. 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();
Moving an alternate domain name to a different distribution
When you try to add an alternate domain name to a distribution but the alternate domain name is already in use on a different distribution, you get a CNAMEAlreadyExists
error (One or more of the CNAMEs you provided are already associated with a different resource).
In that case, you might want to move the existing alternate domain name from one distribution (the source distribution) to another (the target distribution). The following steps are an overview of the process. For more information, see Moving an alternate domain name to a different distribution.
- Deploy the stack with the target distribution. The
certificate
property must be specified but thedomainNames
should be absent. - Move the alternate domain name by running CloudFront
associate-alias
command. For the example and preconditions, see the AWS documentation above. - 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
.
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();
Multiple Behaviors & Origins
Each distribution has a default behavior which applies to all requests to that distribution; additional behaviors may be specified for a given URL path pattern. Behaviors allow routing with multiple origins, controlling which HTTP methods to support, whether to require users to use HTTPS, and what query strings or cookies to forward to your origin, among others.
The properties of the default behavior can be adjusted as part of the distribution creation. The following example shows configuring the HTTP methods and viewer protocol policy of the cache.
// Create a Distribution with configured HTTP methods and viewer protocol policy of the cache. 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();
Additional behaviors can be specified at creation, or added after the initial creation. Each additional behavior is associated with an origin,
and enable customization for a specific set of resources based on a URL path pattern. For example, we can add a behavior to myWebDistribution
to
override the default viewer protocol policy for all of the images.
// Add a behavior to a Distribution after initial creation. Bucket myBucket; Distribution myWebDistribution; myWebDistribution.addBehavior("/images/*.jpg", new S3Origin(myBucket), AddBehaviorOptions.builder() .viewerProtocolPolicy(ViewerProtocolPolicy.REDIRECT_TO_HTTPS) .build());
These behaviors can also be specified at distribution creation time.
// 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();
Customizing Cache Keys and TTLs with Cache Policies
You can use a cache policy to improve your cache hit ratio by controlling the values (URL query strings, HTTP headers, and cookies) that are included in the cache key, and/or adjusting how long items remain in the cache via the time-to-live (TTL) settings. CloudFront provides some predefined cache policies, known as managed policies, for common use cases. You can use these managed policies, or you can create your own cache policy that’s specific to your needs. See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html for more details.
// Using an existing cache policy for a Distribution S3Origin bucketOrigin; Distribution.Builder.create(this, "myDistManagedPolicy") .defaultBehavior(BehaviorOptions.builder() .origin(bucketOrigin) .cachePolicy(CachePolicy.CACHING_OPTIMIZED) .build()) .build();
// 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();
Customizing Origin Requests with Origin Request Policies
When CloudFront makes a request to an origin, the URL path, request body (if present), and a few standard headers are included. Other information from the viewer request, such as URL query strings, HTTP headers, and cookies, is not included in the origin request by default. You can use an origin request policy to control the information that’s included in an origin request. CloudFront provides some predefined origin request policies, known as managed policies, for common use cases. You can use these managed policies, or you can create your own origin request policy that’s specific to your needs. See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html for more details.
// Using an existing origin request policy for a Distribution S3Origin bucketOrigin; Distribution.Builder.create(this, "myDistManagedPolicy") .defaultBehavior(BehaviorOptions.builder() .origin(bucketOrigin) .originRequestPolicy(OriginRequestPolicy.CORS_S3_ORIGIN) .build()) .build();
// 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();
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
// 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(true).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();
Validating signed URLs or signed cookies with Trusted Key Groups
CloudFront Distribution supports validating signed URLs or signed cookies using key groups. When a cache behavior contains trusted key groups, CloudFront requires signed URLs or signed cookies for all requests that match the cache behavior.
// Validating signed URLs or signed cookies with Trusted Key Groups // public key in PEM format 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();
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:
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();
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, theEdgeFunction
construct can be used. TheEdgeFunction
construct will automatically request a function inus-east-1
, regardless of the region of the current stack.EdgeFunction
has the same interface asFunction
and can be created and used interchangeably. Please note that usingEdgeFunction
requires that theus-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
.
// 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();
If the stack is not in us-east-1
, and you need references from different applications on the same account,
you can also set a specific stack ID for each Lambda@Edge.
// Setting stackIds for EdgeFunctions that can be referenced from different applications // on the same account. 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();
Lambda@Edge functions can also be associated with additional behaviors, either at or after Distribution creation time.
// Associating a Lambda@Edge function with additional behaviors. 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());
Adding an existing Lambda@Edge function created in a different stack to a CloudFront distribution.
// Adding an existing Lambda@Edge function created in a different stack // to a CloudFront distribution. 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(new S3Origin(s3Bucket)) .edgeLambdas(List.of(EdgeLambda.builder() .functionVersion(functionVersion) .eventType(LambdaEdgeEventType.VIEWER_REQUEST) .build())) .build()) .build();
CloudFront Function
You can also deploy CloudFront functions and add them to a CloudFront distribution.
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();
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.
Function.Builder.create(this, "Function") .code(FunctionCode.fromInline("function handler(event) { return event.request }")) .runtime(FunctionRuntime.JS_2_0) .autoPublish(false) .build();
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:
KeyValueStore store = new KeyValueStore(this, "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.
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();
The Key Value Store can then be associated to a function using the cloudfront-js-2.0
runtime
or newer:
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();
Logging
You can configure CloudFront to create log files that contain detailed information about every user request that CloudFront receives. The logs can go to either an existing bucket, or a bucket will be created for you.
// Configure logging for Distributions // Simplest form - creates a new bucket and logs to it. // 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();
CloudFront Distribution Metrics
You can view operational metrics about your CloudFront distributions.
Default CloudFront Distribution Metrics
The following metrics are available by default for all CloudFront distributions:
- Total requests: The total number of viewer requests received by CloudFront for all HTTP methods and for both HTTP and HTTPS requests.
- Total bytes uploaded: The total number of bytes that viewers uploaded to your origin with CloudFront, using POST and PUT requests.
- Total bytes downloaded: The total number of bytes downloaded by viewers for GET, HEAD, and OPTIONS requests.
- Total error rate: The percentage of all viewer requests for which the response's HTTP status code was 4xx or 5xx.
- 4xx error rate: The percentage of all viewer requests for which the response's HTTP status code was 4xx.
- 5xx error rate: The percentage of all viewer requests for which the response's HTTP status code was 5xx.
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();
Additional CloudFront Distribution Metrics
You can enable additional CloudFront distribution metrics, which include the following metrics:
- 4xx and 5xx error rates: View 4xx and 5xx error rates by the specific HTTP status code, as a percentage of total requests.
- Origin latency: See the total time spent from when CloudFront receives a request to when it provides a response to the network (not the viewer), for responses that are served from the origin, not the CloudFront cache.
- Cache hit rate: View cache hits as a percentage of total cacheable requests, excluding errors.
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();
HTTP Versions
You can configure CloudFront to use a particular version of the HTTP protocol. By default,
newly created distributions use HTTP/2 but can be configured to use both HTTP/2 and HTTP/3 or
just HTTP/3. For all supported HTTP versions, see the HttpVerson
enum.
// Configure a distribution to use HTTP/2 and HTTP/3 // 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();
Importing Distributions
Existing distributions can be imported as well; note that like most imported constructs, an imported distribution cannot be modified. However, it can be used as a reference for other higher-level constructs.
// Using a reference to an imported Distribution IDistribution distribution = Distribution.fromDistributionAttributes(this, "ImportedDist", DistributionAttributes.builder() .domainName("d111111abcdef8.cloudfront.net") .distributionId("012345ABCDEF") .build());
Permissions
Use the grant()
method to allow actions on the distribution.
grantCreateInvalidation()
is a shorthand to allow CreateInvalidation
.
Distribution distribution; Function lambdaFn; distribution.grant(lambdaFn, "cloudfront:ListInvalidations", "cloudfront:GetInvalidation"); distribution.grantCreateInvalidation(lambdaFn);
Realtime Log Config
CloudFront supports realtime log delivery from your distribution to a Kinesis stream.
See Real-time logs in the CloudFront User Guide.
Example:
// Adding realtime logs config to a Cloudfront Distribution on default behavior. import 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();
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
|
After switching constructs, you need to maintain the same logical ID for the underlying CfnDistribution if you wish to avoid the deletion and recreation of your distribution. To do this, use escape hatches to override the logical ID created by the new Distribution construct with the logical ID created by the old construct.
Example:
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");
Behaviors
The modern API makes use of the CloudFront Origins module to easily configure your origin. Replace your origin configuration with the relevant CloudFront Origins class. For example, here's a behavior with an S3 origin:
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();
Becomes:
Bucket sourceBucket; Distribution distribution = Distribution.Builder.create(this, "MyCfWebDistribution") .defaultBehavior(BehaviorOptions.builder() .origin(new S3Origin(sourceBucket)) .build()) .build();
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.
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();
Becomes:
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();
Certificates
If you are using an ACM certificate, you can pass the certificate directly to the certificate
prop.
Any aliases used before in the ViewerCertificate
class should be passed in to the domainNames
prop in the modern API.
import 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();
Becomes:
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();
IAM certificates aren't directly supported by the new API, but can be easily configured through escape hatches
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();
Becomes:
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");
Other changes
A number of default settings have changed on the new API when creating a new distribution, behavior, and origin.
After making the major changes needed for the migration, run cdk diff
to see what settings have changed.
If no changes are desired during migration, you will at the least be able to use escape hatches to override what the CDK synthesizes, if you can't change the properties directly.
CloudFrontWebDistribution API
The
CloudFrontWebDistribution
construct is the original construct written for working with CloudFront distributions. Users are encouraged to use the newerDistribution
instead, as it has a simpler interface and receives new features faster.
Example usage:
// 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();
Viewer certificate
By default, CloudFront Web Distributions will answer HTTPS requests with CloudFront's default certificate,
only containing the distribution domainName
(e.g. d111111abcdef8.cloudfront.net).
You can customize the viewer certificate property to provide a custom certificate and/or list of domain name aliases to fit your needs.
See Using Alternate Domain Names and HTTPS in the CloudFront User Guide.
Default certificate
You can customize the default certificate aliases. This is intended to be used in combination with CNAME records in your DNS zone.
Example:
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();
ACM certificate
You can change the default certificate by one stored AWS Certificate Manager, or ACM. Those certificate can either be generated by AWS, or purchased by another CA imported into ACM.
For more information, see the aws-certificatemanager module documentation or Importing Certificates into AWS Certificate Manager in the AWS Certificate Manager User Guide.
Example:
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();
IAM certificate
You can also import a certificate into the IAM certificate store.
See Importing an SSL/TLS Certificate in the CloudFront User Guide.
Example:
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();
Trusted Key Groups
CloudFront Web Distributions supports validating signed URLs or signed cookies using key groups. When a cache behavior contains trusted key groups, CloudFront requires signed URLs or signed cookies for all requests that match the cache behavior.
Example:
// Using trusted key groups for Cloudfront Web Distributions. 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();
Restrictions
CloudFront supports adding restrictions to your distribution.
See Restricting the Geographic Distribution of Your Content in the CloudFront User Guide.
Example:
// Adding restrictions to a Cloudfront Web Distribution. 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();
Connection behaviors between CloudFront and your origin
CloudFront provides you even more control over the connection behaviors between CloudFront and your origin. You can now configure the number of connection attempts CloudFront will make to your origin and the origin connection timeout for each attempt.
See Origin Connection Attempts
Example usage:
// Configuring connection behaviors between Cloudfront and your origin 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();
Origin Fallback
In case the origin source is not available and answers with one of the specified status codes the failover origin source will be used.
// Configuring origin fallback options for the CloudFrontWebDistribution // 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", "myoriginbucket")) .originPath("/") .originHeaders(Map.of( "myHeader", "42")) .originShieldRegion("us-west-2") .build()) .failoverS3OriginSource(S3OriginConfig.builder() .s3BucketSource(Bucket.fromBucketName(this, "aBucketFallback", "myoriginbucketfallback")) .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();
KeyGroup & PublicKey API
You can create a key group to use with CloudFront signed URLs and signed cookies You can add public keys to use with CloudFront features such as signed URLs, signed cookies, and field-level encryption.
The following example command uses OpenSSL to generate an RSA key pair with a length of 2048 bits and save to the file named private_key.pem
.
openssl genrsa -out private_key.pem 2048
The resulting file contains both the public and the private key. The following example command extracts the public key from the file named private_key.pem
and stores it in public_key.pem
.
openssl rsa -pubout -in private_key.pem -out public_key.pem
Note: Don't forget to copy/paste the contents of public_key.pem
file including -----BEGIN PUBLIC KEY-----
and -----END PUBLIC KEY-----
lines into encodedKey
parameter when creating a PublicKey
.
Example:
// Create a key group to use with CloudFront signed URLs and signed cookies. // 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();
See:
- https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html
- https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html
-
ClassDescriptionOptions for adding a new behavior to a Distribution.A builder for
AddBehaviorOptions
An implementation forAddBehaviorOptions
The HTTP methods that the Behavior will accept requests on.An import source from a local file.A fluent builder forAssetImportSource
.A CloudFront behavior wrapper.A builder forBehavior
An implementation forBehavior
Options for creating a new behavior.A builder forBehaviorOptions
An implementation forBehaviorOptions
Determines whether any cookies in viewer requests are included in the cache key and automatically included in requests that CloudFront sends to the origin.The HTTP methods that the Behavior will cache requests on.Determines whether any HTTP headers are included in the cache key and automatically included in requests that CloudFront sends to the origin.A Cache Policy configuration.A fluent builder forCachePolicy
.Properties for creating a Cache Policy.A builder forCachePolicyProps
An implementation forCachePolicyProps
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.A cache policy.A fluent builder forCfnCachePolicy
.A cache policy configuration.A builder forCfnCachePolicy.CachePolicyConfigProperty
An implementation forCfnCachePolicy.CachePolicyConfigProperty
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.A builder forCfnCachePolicy.CookiesConfigProperty
An implementation forCfnCachePolicy.CookiesConfigProperty
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.A builder forCfnCachePolicy.HeadersConfigProperty
An implementation forCfnCachePolicy.HeadersConfigProperty
This object determines the values that CloudFront includes in the cache key.An implementation forCfnCachePolicy.ParametersInCacheKeyAndForwardedToOriginProperty
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.A builder forCfnCachePolicy.QueryStringsConfigProperty
An implementation forCfnCachePolicy.QueryStringsConfigProperty
Properties for defining aCfnCachePolicy
.A builder forCfnCachePolicyProps
An implementation forCfnCachePolicyProps
The request to create a new origin access identity (OAI).A fluent builder forCfnCloudFrontOriginAccessIdentity
.Origin access identity configuration.An implementation forCfnCloudFrontOriginAccessIdentity.CloudFrontOriginAccessIdentityConfigProperty
Properties for defining aCfnCloudFrontOriginAccessIdentity
.A builder forCfnCloudFrontOriginAccessIdentityProps
An implementation forCfnCloudFrontOriginAccessIdentityProps
Creates a continuous deployment policy that routes a subset of production traffic from a primary distribution to a staging distribution.A fluent builder forCfnContinuousDeploymentPolicy
.Contains the configuration for a continuous deployment policy.An implementation forCfnContinuousDeploymentPolicy.ContinuousDeploymentPolicyConfigProperty
Session stickiness provides the ability to define multiple requests from a single viewer as a single session.An implementation forCfnContinuousDeploymentPolicy.SessionStickinessConfigProperty
Determines which HTTP requests are sent to the staging distribution.A builder forCfnContinuousDeploymentPolicy.SingleHeaderConfigProperty
An implementation forCfnContinuousDeploymentPolicy.SingleHeaderConfigProperty
Defines a single header policy for a CloudFront distribution.An implementation forCfnContinuousDeploymentPolicy.SingleHeaderPolicyConfigProperty
This configuration determines the percentage of HTTP requests that are sent to the staging distribution.A builder forCfnContinuousDeploymentPolicy.SingleWeightConfigProperty
An implementation forCfnContinuousDeploymentPolicy.SingleWeightConfigProperty
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.An implementation forCfnContinuousDeploymentPolicy.SingleWeightPolicyConfigProperty
The traffic configuration of your continuous deployment.A builder forCfnContinuousDeploymentPolicy.TrafficConfigProperty
An implementation forCfnContinuousDeploymentPolicy.TrafficConfigProperty
Properties for defining aCfnContinuousDeploymentPolicy
.A builder forCfnContinuousDeploymentPolicyProps
An implementation forCfnContinuousDeploymentPolicyProps
A distribution tells CloudFront where you want content to be delivered from, and the details about how to track and manage content delivery.A fluent builder forCfnDistribution
.A complex type that describes how CloudFront processes requests.A builder forCfnDistribution.CacheBehaviorProperty
An implementation forCfnDistribution.CacheBehaviorProperty
This field is deprecated.A builder forCfnDistribution.CookiesProperty
An implementation forCfnDistribution.CookiesProperty
A complex type that controls:.A builder forCfnDistribution.CustomErrorResponseProperty
An implementation forCfnDistribution.CustomErrorResponseProperty
A custom origin.A builder forCfnDistribution.CustomOriginConfigProperty
An implementation forCfnDistribution.CustomOriginConfigProperty
A complex type that describes the default cache behavior if you don't specify aCacheBehavior
element or if request URLs don't match any of the values ofPathPattern
inCacheBehavior
elements.A builder forCfnDistribution.DefaultCacheBehaviorProperty
An implementation forCfnDistribution.DefaultCacheBehaviorProperty
A distribution configuration.A builder forCfnDistribution.DistributionConfigProperty
An implementation forCfnDistribution.DistributionConfigProperty
This field is deprecated.A builder forCfnDistribution.ForwardedValuesProperty
An implementation forCfnDistribution.ForwardedValuesProperty
A CloudFront function that is associated with a cache behavior in a CloudFront distribution.A builder forCfnDistribution.FunctionAssociationProperty
An implementation forCfnDistribution.FunctionAssociationProperty
A complex type that controls the countries in which your content is distributed.A builder forCfnDistribution.GeoRestrictionProperty
An implementation forCfnDistribution.GeoRestrictionProperty
A complex type that contains a Lambda@Edge function association.A builder forCfnDistribution.LambdaFunctionAssociationProperty
An implementation forCfnDistribution.LambdaFunctionAssociationProperty
A custom origin.A builder forCfnDistribution.LegacyCustomOriginProperty
An implementation forCfnDistribution.LegacyCustomOriginProperty
The origin as an Amazon S3 bucket.A builder forCfnDistribution.LegacyS3OriginProperty
An implementation forCfnDistribution.LegacyS3OriginProperty
A complex type that controls whether access logs are written for the distribution.A builder forCfnDistribution.LoggingProperty
An implementation forCfnDistribution.LoggingProperty
A complex type that containsHeaderName
andHeaderValue
elements, if any, for this distribution.A builder forCfnDistribution.OriginCustomHeaderProperty
An implementation forCfnDistribution.OriginCustomHeaderProperty
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.A builder forCfnDistribution.OriginGroupFailoverCriteriaProperty
An implementation forCfnDistribution.OriginGroupFailoverCriteriaProperty
An origin in an origin group.A builder forCfnDistribution.OriginGroupMemberProperty
An implementation forCfnDistribution.OriginGroupMemberProperty
A complex data type for the origins included in an origin group.A builder forCfnDistribution.OriginGroupMembersProperty
An implementation forCfnDistribution.OriginGroupMembersProperty
An origin group includes two origins (a primary origin and a second origin to failover to) and a failover criteria that you specify.A builder forCfnDistribution.OriginGroupProperty
An implementation forCfnDistribution.OriginGroupProperty
A complex data type for the origin groups specified for a distribution.A builder forCfnDistribution.OriginGroupsProperty
An implementation forCfnDistribution.OriginGroupsProperty
An origin.A builder forCfnDistribution.OriginProperty
An implementation forCfnDistribution.OriginProperty
CloudFront Origin Shield.A builder forCfnDistribution.OriginShieldProperty
An implementation forCfnDistribution.OriginShieldProperty
A complex type that identifies ways in which you want to restrict distribution of your content.A builder forCfnDistribution.RestrictionsProperty
An implementation forCfnDistribution.RestrictionsProperty
A complex type that contains information about the Amazon S3 origin.A builder forCfnDistribution.S3OriginConfigProperty
An implementation forCfnDistribution.S3OriginConfigProperty
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.A builder forCfnDistribution.StatusCodesProperty
An implementation forCfnDistribution.StatusCodesProperty
A complex type that determines the distribution's SSL/TLS configuration for communicating with viewers.A builder forCfnDistribution.ViewerCertificateProperty
An implementation forCfnDistribution.ViewerCertificateProperty
Properties for defining aCfnDistribution
.A builder forCfnDistributionProps
An implementation forCfnDistributionProps
Creates a CloudFront function.A fluent builder forCfnFunction
.Contains configuration information about a CloudFront function.A builder forCfnFunction.FunctionConfigProperty
An implementation forCfnFunction.FunctionConfigProperty
Contains metadata about a CloudFront function.A builder forCfnFunction.FunctionMetadataProperty
An implementation forCfnFunction.FunctionMetadataProperty
The key value store association.A builder forCfnFunction.KeyValueStoreAssociationProperty
An implementation forCfnFunction.KeyValueStoreAssociationProperty
Properties for defining aCfnFunction
.A builder forCfnFunctionProps
An implementation forCfnFunctionProps
A key group.A fluent builder forCfnKeyGroup
.A key group configuration.A builder forCfnKeyGroup.KeyGroupConfigProperty
An implementation forCfnKeyGroup.KeyGroupConfigProperty
Properties for defining aCfnKeyGroup
.A builder forCfnKeyGroupProps
An implementation forCfnKeyGroupProps
The key value store.A fluent builder forCfnKeyValueStore
.The import source for the key value store.A builder forCfnKeyValueStore.ImportSourceProperty
An implementation forCfnKeyValueStore.ImportSourceProperty
Properties for defining aCfnKeyValueStore
.A builder forCfnKeyValueStoreProps
An implementation forCfnKeyValueStoreProps
A monitoring subscription.A fluent builder forCfnMonitoringSubscription
.A monitoring subscription.A builder forCfnMonitoringSubscription.MonitoringSubscriptionProperty
An implementation forCfnMonitoringSubscription.MonitoringSubscriptionProperty
A subscription configuration for additional CloudWatch metrics.An implementation forCfnMonitoringSubscription.RealtimeMetricsSubscriptionConfigProperty
Properties for defining aCfnMonitoringSubscription
.A builder forCfnMonitoringSubscriptionProps
An implementation forCfnMonitoringSubscriptionProps
Creates a new origin access control in CloudFront.A fluent builder forCfnOriginAccessControl
.Creates a new origin access control in CloudFront.A builder forCfnOriginAccessControl.OriginAccessControlConfigProperty
An implementation forCfnOriginAccessControl.OriginAccessControlConfigProperty
Properties for defining aCfnOriginAccessControl
.A builder forCfnOriginAccessControlProps
An implementation forCfnOriginAccessControlProps
An origin request policy.A fluent builder forCfnOriginRequestPolicy
.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.A builder forCfnOriginRequestPolicy.CookiesConfigProperty
An implementation forCfnOriginRequestPolicy.CookiesConfigProperty
An object that determines whether any HTTP headers (and if so, which headers) are included in requests that CloudFront sends to the origin.A builder forCfnOriginRequestPolicy.HeadersConfigProperty
An implementation forCfnOriginRequestPolicy.HeadersConfigProperty
An origin request policy configuration.A builder forCfnOriginRequestPolicy.OriginRequestPolicyConfigProperty
An implementation forCfnOriginRequestPolicy.OriginRequestPolicyConfigProperty
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.A builder forCfnOriginRequestPolicy.QueryStringsConfigProperty
An implementation forCfnOriginRequestPolicy.QueryStringsConfigProperty
Properties for defining aCfnOriginRequestPolicy
.A builder forCfnOriginRequestPolicyProps
An implementation forCfnOriginRequestPolicyProps
A public key that you can use with signed URLs and signed cookies , or with field-level encryption .A fluent builder forCfnPublicKey
.Configuration information about a public key that you can use with signed URLs and signed cookies , or with field-level encryption .A builder forCfnPublicKey.PublicKeyConfigProperty
An implementation forCfnPublicKey.PublicKeyConfigProperty
Properties for defining aCfnPublicKey
.A builder forCfnPublicKeyProps
An implementation forCfnPublicKeyProps
A real-time log configuration.A fluent builder forCfnRealtimeLogConfig
.Contains information about the Amazon Kinesis data stream where you are sending real-time log data in a real-time log configuration.A builder forCfnRealtimeLogConfig.EndPointProperty
An implementation forCfnRealtimeLogConfig.EndPointProperty
Contains information about the Amazon Kinesis data stream where you are sending real-time log data.A builder forCfnRealtimeLogConfig.KinesisStreamConfigProperty
An implementation forCfnRealtimeLogConfig.KinesisStreamConfigProperty
Properties for defining aCfnRealtimeLogConfig
.A builder forCfnRealtimeLogConfigProps
An implementation forCfnRealtimeLogConfigProps
A response headers policy.A list of HTTP header names that CloudFront includes as values for theAccess-Control-Allow-Headers
HTTP response header.An implementation forCfnResponseHeadersPolicy.AccessControlAllowHeadersProperty
A list of HTTP methods that CloudFront includes as values for theAccess-Control-Allow-Methods
HTTP response header.An implementation forCfnResponseHeadersPolicy.AccessControlAllowMethodsProperty
A list of origins (domain names) that CloudFront can use as the value for theAccess-Control-Allow-Origin
HTTP response header.An implementation forCfnResponseHeadersPolicy.AccessControlAllowOriginsProperty
A list of HTTP headers that CloudFront includes as values for theAccess-Control-Expose-Headers
HTTP response header.An implementation forCfnResponseHeadersPolicy.AccessControlExposeHeadersProperty
A fluent builder forCfnResponseHeadersPolicy
.The policy directives and their values that CloudFront includes as values for theContent-Security-Policy
HTTP response header.A builder forCfnResponseHeadersPolicy.ContentSecurityPolicyProperty
An implementation forCfnResponseHeadersPolicy.ContentSecurityPolicyProperty
Determines whether CloudFront includes theX-Content-Type-Options
HTTP response header with its value set tonosniff
.A builder forCfnResponseHeadersPolicy.ContentTypeOptionsProperty
An implementation forCfnResponseHeadersPolicy.ContentTypeOptionsProperty
A configuration for a set of HTTP response headers that are used for cross-origin resource sharing (CORS).A builder forCfnResponseHeadersPolicy.CorsConfigProperty
An implementation forCfnResponseHeadersPolicy.CorsConfigProperty
An HTTP response header name and its value.A builder forCfnResponseHeadersPolicy.CustomHeaderProperty
An implementation forCfnResponseHeadersPolicy.CustomHeaderProperty
A list of HTTP response header names and their values.A builder forCfnResponseHeadersPolicy.CustomHeadersConfigProperty
An implementation forCfnResponseHeadersPolicy.CustomHeadersConfigProperty
Determines whether CloudFront includes theX-Frame-Options
HTTP response header and the header's value.A builder forCfnResponseHeadersPolicy.FrameOptionsProperty
An implementation forCfnResponseHeadersPolicy.FrameOptionsProperty
Determines whether CloudFront includes theReferrer-Policy
HTTP response header and the header's value.A builder forCfnResponseHeadersPolicy.ReferrerPolicyProperty
An implementation forCfnResponseHeadersPolicy.ReferrerPolicyProperty
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.A builder forCfnResponseHeadersPolicy.RemoveHeaderProperty
An implementation forCfnResponseHeadersPolicy.RemoveHeaderProperty
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.A builder forCfnResponseHeadersPolicy.RemoveHeadersConfigProperty
An implementation forCfnResponseHeadersPolicy.RemoveHeadersConfigProperty
A response headers policy configuration.An implementation forCfnResponseHeadersPolicy.ResponseHeadersPolicyConfigProperty
A configuration for a set of security-related HTTP response headers.A builder forCfnResponseHeadersPolicy.SecurityHeadersConfigProperty
An implementation forCfnResponseHeadersPolicy.SecurityHeadersConfigProperty
A configuration for enabling theServer-Timing
header in HTTP responses sent from CloudFront.An implementation forCfnResponseHeadersPolicy.ServerTimingHeadersConfigProperty
Determines whether CloudFront includes theStrict-Transport-Security
HTTP response header and the header's value.A builder forCfnResponseHeadersPolicy.StrictTransportSecurityProperty
An implementation forCfnResponseHeadersPolicy.StrictTransportSecurityProperty
Determines whether CloudFront includes theX-XSS-Protection
HTTP response header and the header's value.A builder forCfnResponseHeadersPolicy.XSSProtectionProperty
An implementation forCfnResponseHeadersPolicy.XSSProtectionProperty
Properties for defining aCfnResponseHeadersPolicy
.A builder forCfnResponseHeadersPolicyProps
An implementation forCfnResponseHeadersPolicyProps
This resource is deprecated.A fluent builder forCfnStreamingDistribution
.A complex type that controls whether access logs are written for the streaming distribution.A builder forCfnStreamingDistribution.LoggingProperty
An implementation forCfnStreamingDistribution.LoggingProperty
A complex type that contains information about the Amazon S3 bucket from which you want CloudFront to get your media files for distribution.A builder forCfnStreamingDistribution.S3OriginProperty
An implementation forCfnStreamingDistribution.S3OriginProperty
The RTMP distribution's configuration information.An implementation forCfnStreamingDistribution.StreamingDistributionConfigProperty
A list of AWS accounts whose public keys CloudFront can use to verify the signatures of signed URLs and signed cookies.A builder forCfnStreamingDistribution.TrustedSignersProperty
An implementation forCfnStreamingDistribution.TrustedSignersProperty
Properties for defining aCfnStreamingDistribution
.A builder forCfnStreamingDistributionProps
An implementation forCfnStreamingDistributionProps
Enums for the methods CloudFront can cache.An enum for the supported methods to a CloudFront distribution.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.A fluent builder forCloudFrontWebDistribution
.Attributes used to import a Distribution.A builder forCloudFrontWebDistributionAttributes
An implementation forCloudFrontWebDistributionAttributes
Example:A builder forCloudFrontWebDistributionProps
An implementation forCloudFrontWebDistributionProps
A custom origin configuration.A builder forCustomOriginConfig
An implementation forCustomOriginConfig
A CloudFront distribution with associated origin(s) and caching behavior(s).A fluent builder forDistribution
.Attributes used to import a Distribution.A builder forDistributionAttributes
An implementation forDistributionAttributes
Properties for a Distribution.A builder forDistributionProps
An implementation forDistributionProps
Represents a Lambda function version and event type when using Lambda@Edge.A builder forEdgeLambda
An implementation forEdgeLambda
Represents the endpoints available for targetting within a realtime log config resource.Options for configuring custom error responses.A builder forErrorResponse
An implementation forErrorResponse
HTTP status code to failover to second origin.Options when reading the function's code from an external file.A builder forFileCodeOptions
An implementation forFileCodeOptions
A CloudFront Function.A fluent builder forFunction
.Represents a CloudFront function and event type when using CF Functions.A builder forFunctionAssociation
An implementation forFunctionAssociation
Attributes of an existing CloudFront Function to import it.A builder forFunctionAttributes
An implementation forFunctionAttributes
Represents the function's source code.The type of events that a CloudFront function can be invoked in response to.Properties for creating a CloudFront Function.A builder forFunctionProps
An implementation forFunctionProps
The function's runtime environment version.Controls the countries in which content is distributed.Enum representing possible values of the X-Frame-Options HTTP response header.Enum representing possible values of the Referrer-Policy HTTP response header.Maximum HTTP version to support.Represents a Cache Policy.Internal default implementation forICachePolicy
.A proxy class which represents a concrete javascript instance of this type.Interface for CloudFront distributions.Internal default implementation forIDistribution
.A proxy class which represents a concrete javascript instance of this type.Represents a CloudFront Function.Internal default implementation forIFunction
.A proxy class which represents a concrete javascript instance of this type.Represents a Key Group.Internal default implementation forIKeyGroup
.A proxy class which represents a concrete javascript instance of this type.A CloudFront Key Value Store.Internal default implementation forIKeyValueStore
.A proxy class which represents a concrete javascript instance of this type.The data to be imported to the key value store.An import source from an inline string.Represents the concept of a CloudFront Origin.Internal default implementation forIOrigin
.A proxy class which represents a concrete javascript instance of this type.Interface for CloudFront OriginAccessIdentity.Internal default implementation forIOriginAccessIdentity
.A proxy class which represents a concrete javascript instance of this type.Represents a Origin Request Policy.Internal default implementation forIOriginRequestPolicy
.A proxy class which represents a concrete javascript instance of this type.Represents a Public Key.Internal default implementation forIPublicKey
.A proxy class which represents a concrete javascript instance of this type.Represents Realtime Log Configuration.Internal default implementation forIRealtimeLogConfig
.A proxy class which represents a concrete javascript instance of this type.Represents a response headers policy.Internal default implementation forIResponseHeadersPolicy
.A proxy class which represents a concrete javascript instance of this type.A Key Group configuration.A fluent builder forKeyGroup
.Properties for creating a Public Key.A builder forKeyGroupProps
An implementation forKeyGroupProps
A CloudFront Key Value Store.A fluent builder forKeyValueStore
.The properties to create a Key Value Store.A builder forKeyValueStoreProps
An implementation forKeyValueStoreProps
The type of events that a Lambda@Edge function can be invoked in response to.Example:A builder forLambdaFunctionAssociation
An implementation forLambdaFunctionAssociation
Logging configuration for incoming requests.A builder forLoggingConfiguration
An implementation forLoggingConfiguration
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.A fluent builder forOriginAccessIdentity
.Properties of CloudFront OriginAccessIdentity.A builder forOriginAccessIdentityProps
An implementation forOriginAccessIdentityProps
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.The struct returned fromIOrigin.bind
.A builder forOriginBindConfig
An implementation forOriginBindConfig
Options passed to Origin.bind().A builder forOriginBindOptions
An implementation forOriginBindOptions
The failover configuration used for Origin Groups, returned inOriginBindConfig.failoverConfig
.A builder forOriginFailoverConfig
An implementation forOriginFailoverConfig
Options to define an Origin.A builder forOriginOptions
An implementation forOriginOptions
Properties to define an Origin.A builder forOriginProps
An implementation forOriginProps
Defines what protocols CloudFront will use to connect to an origin.Determines whether any cookies in viewer requests (and if so, which cookies) are included in requests that CloudFront sends to the origin.Determines whether any HTTP headers (and if so, which headers) are included in requests that CloudFront sends to the origin.A Origin Request Policy configuration.A fluent builder forOriginRequestPolicy
.Properties for creating a Origin Request Policy.A builder forOriginRequestPolicyProps
An implementation forOriginRequestPolicyProps
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.The price class determines how many edge locations CloudFront will use for your distribution.A Public Key Configuration.A fluent builder forPublicKey
.Properties for creating a Public Key.A builder forPublicKeyProps
An implementation forPublicKeyProps
A Realtime Log Config configuration.A fluent builder forRealtimeLogConfig
.Properties for defining a RealtimeLogConfig resource.A builder forRealtimeLogConfigProps
An implementation forRealtimeLogConfigProps
An HTTP response header name and its value.A builder forResponseCustomHeader
An implementation forResponseCustomHeader
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.A builder forResponseCustomHeadersBehavior
An implementation forResponseCustomHeadersBehavior
The policy directives and their values that CloudFront includes as values for the Content-Security-Policy HTTP response header.A builder forResponseHeadersContentSecurityPolicy
An implementation forResponseHeadersContentSecurityPolicy
Determines whether CloudFront includes the X-Content-Type-Options HTTP response header with its value set to nosniff.A builder forResponseHeadersContentTypeOptions
An implementation forResponseHeadersContentTypeOptions
Configuration for a set of HTTP response headers that are used for cross-origin resource sharing (CORS).A builder forResponseHeadersCorsBehavior
An implementation forResponseHeadersCorsBehavior
Determines whether CloudFront includes the X-Frame-Options HTTP response header and the header’s value.A builder forResponseHeadersFrameOptions
An implementation forResponseHeadersFrameOptions
A Response Headers Policy configuration.A fluent builder forResponseHeadersPolicy
.Properties for creating a Response Headers Policy.A builder forResponseHeadersPolicyProps
An implementation forResponseHeadersPolicyProps
Determines whether CloudFront includes the Referrer-Policy HTTP response header and the header’s value.A builder forResponseHeadersReferrerPolicy
An implementation forResponseHeadersReferrerPolicy
Determines whether CloudFront includes the Strict-Transport-Security HTTP response header and the header’s value.A builder forResponseHeadersStrictTransportSecurity
An implementation forResponseHeadersStrictTransportSecurity
Determines whether CloudFront includes the X-XSS-Protection HTTP response header and the header’s value.A builder forResponseHeadersXSSProtection
An implementation forResponseHeadersXSSProtection
Configuration for a set of security-related HTTP response headers.A builder forResponseSecurityHeadersBehavior
An implementation forResponseSecurityHeadersBehavior
An import source from an S3 object.S3 origin configuration for CloudFront.A builder forS3OriginConfig
An implementation forS3OriginConfig
The minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections.A source configuration is a wrapper for CloudFront origins and behaviors.A builder forSourceConfiguration
An implementation forSourceConfiguration
The SSL method CloudFront will use for your distribution.Viewer certificate configuration class.Example:A builder forViewerCertificateOptions
An implementation forViewerCertificateOptions
How HTTPs should be handled with your distribution.