1.204.0 • Published 9 months ago

@aws-cdk/aws-cloudfront v1.204.0

Weekly downloads
261,969
License
Apache-2.0
Repository
github
Last release
9 months ago

Amazon CloudFront Construct Library


End-of-Support

AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2.

For more information on how to migrate, see the Migrating to AWS CDK v2 guide.

doc: https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html


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/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.
const myBucket = new s3.Bucket(this, 'myBucket');
new cloudfront.Distribution(this, 'myDist', {
  defaultBehavior: { origin: new origins.S3Origin(myBucket) },
});

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

From an HTTP endpoint

Origins can also be created from any other HTTP endpoint, given the domain name, and optionally, other origin properties.

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

Domain Names and Certificates

When you create a distribution, CloudFront assigns a domain name for the distribution, for example: d111111abcdef8.cloudfront.net; this value can be retrieved from distribution.distributionDomainName. CloudFront distributions use a default certificate (*.cloudfront.net) to support HTTPS by default. If you want to use your own domain name, such as www.example.com, you must associate a certificate with your distribution that contains your domain name, and provide one (or more) domain names from the certificate for the distribution.

The certificate must be present in the AWS Certificate Manager (ACM) service in the US East (N. Virginia) region; the certificate may either be created by ACM, or created elsewhere and imported into ACM. When a certificate is used, the distribution will support HTTPS connections from SNI only and a minimum protocol version of TLSv1.2_2021 if the @aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021 feature flag is set, and TLSv1.2_2019 otherwise.

// To use your own domain name in a Distribution, you must associate a certificate
import * as acm from '@aws-cdk/aws-certificatemanager';
import * as route53 from '@aws-cdk/aws-route53';

declare const hostedZone: route53.HostedZone;
const myCertificate = new acm.DnsValidatedCertificate(this, 'mySiteCert', {
  domainName: 'www.example.com',
  hostedZone,
});

declare const myBucket: s3.Bucket;
new cloudfront.Distribution(this, 'myDist', {
  defaultBehavior: { origin: new origins.S3Origin(myBucket) },
  domainNames: ['www.example.com'],
  certificate: myCertificate,
});

However, you can customize the minimum protocol version for the certificate while creating the distribution using minimumProtocolVersion property.

// Create a Distribution with a custom domain name and a minimum protocol version.
declare const myBucket: s3.Bucket;
new cloudfront.Distribution(this, 'myDist', {
  defaultBehavior: { origin: new origins.S3Origin(myBucket) },
  domainNames: ['www.example.com'],
  minimumProtocolVersion: cloudfront.SecurityPolicyProtocol.TLS_V1_2016,
  sslSupportMethod: cloudfront.SSLMethod.SNI,
});

Multiple Behaviors & Origins

Each distribution has a default behavior which applies to all requests to that distribution; additional behaviors may be specified for a given URL path pattern. Behaviors allow routing with multiple origins, controlling which HTTP methods to support, whether to require users to use HTTPS, and what query strings or cookies to forward to your origin, among others.

The properties of the default behavior can be adjusted as part of the distribution creation. The following example shows configuring the HTTP methods and viewer protocol policy of the cache.

// Create a Distribution with configured HTTP methods and viewer protocol policy of the cache.
declare const myBucket: s3.Bucket;
const myWebDistribution = new cloudfront.Distribution(this, 'myDist', {
  defaultBehavior: {
    origin: new origins.S3Origin(myBucket),
    allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
    viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
  },
});

Additional behaviors can be specified at creation, or added after the initial creation. Each additional behavior is associated with an origin, and enable customization for a specific set of resources based on a URL path pattern. For example, we can add a behavior to myWebDistribution to override the default viewer protocol policy for all of the images.

// Add a behavior to a Distribution after initial creation.
declare const myBucket: s3.Bucket;
declare const myWebDistribution: cloudfront.Distribution;
myWebDistribution.addBehavior('/images/*.jpg', new origins.S3Origin(myBucket), {
  viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
});

These behaviors can also be specified at distribution creation time.

// Create a Distribution with additional behaviors at creation time.
declare const myBucket: s3.Bucket;
const bucketOrigin = new origins.S3Origin(myBucket);
new cloudfront.Distribution(this, 'myDist', {
  defaultBehavior: {
    origin: bucketOrigin,
    allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
    viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
  },
  additionalBehaviors: {
    '/images/*.jpg': {
      origin: bucketOrigin,
      viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
    },
  },
});

Customizing Cache Keys and TTLs with Cache Policies

You can use a cache policy to improve your cache hit ratio by controlling the values (URL query strings, HTTP headers, and cookies) that are included in the cache key, and/or adjusting how long items remain in the cache via the time-to-live (TTL) settings. CloudFront provides some predefined cache policies, known as managed policies, for common use cases. You can use these managed policies, or you can create your own cache policy that’s specific to your needs. See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html for more details.

// Using an existing cache policy for a Distribution
declare const bucketOrigin: origins.S3Origin;
new cloudfront.Distribution(this, 'myDistManagedPolicy', {
  defaultBehavior: {
    origin: bucketOrigin,
    cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED,
  },
});
// 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,
  },
});

Customizing Origin Requests with Origin Request Policies

When CloudFront makes a request to an origin, the URL path, request body (if present), and a few standard headers are included. Other information from the viewer request, such as URL query strings, HTTP headers, and cookies, is not included in the origin request by default. You can use an origin request policy to control the information that’s included in an origin request. CloudFront provides some predefined origin request policies, known as managed policies, for common use cases. You can use these managed policies, or you can create your own origin request policy that’s specific to your needs. See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html for more details.

// Using an existing origin request policy for a Distribution
declare const bucketOrigin: origins.S3Origin;
new cloudfront.Distribution(this, 'myDistManagedPolicy', {
  defaultBehavior: {
    origin: bucketOrigin,
    originRequestPolicy: cloudfront.OriginRequestPolicy.CORS_S3_ORIGIN,
  },
});
// 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,
  },
});

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
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: true, reportUri: 'https://example.com/csp-report', override: true },
  },
});
new cloudfront.Distribution(this, 'myDistCustomPolicy', {
  defaultBehavior: {
    origin: bucketOrigin,
    responseHeadersPolicy: myResponseHeadersPolicy,
  },
});

Validating signed URLs or signed cookies with Trusted Key Groups

CloudFront Distribution supports validating signed URLs or signed cookies using key groups. When a cache behavior contains trusted key groups, CloudFront requires signed URLs or signed cookies for all requests that match the cache behavior.

// Validating signed URLs or signed cookies with Trusted Key Groups

// public key in PEM format
declare const publicKey: string;
const pubKey = new cloudfront.PublicKey(this, 'MyPubKey', {
  encodedKey: publicKey,
});

const keyGroup = new cloudfront.KeyGroup(this, 'MyKeyGroup', {
  items: [
    pubKey,
  ],
});

new cloudfront.Distribution(this, 'Dist', {
  defaultBehavior: {
    origin: new origins.HttpOrigin('www.example.com'),
    trustedKeyGroups: [
      keyGroup,
    ],
  },
});

Lambda@Edge

Lambda@Edge is an extension of AWS Lambda, a compute service that lets you execute functions that customize the content that CloudFront delivers. You can author Node.js or Python functions in the US East (N. Virginia) region, and then execute them in AWS locations globally that are closer to the viewer, without provisioning or managing servers. Lambda@Edge functions are associated with a specific behavior and event type. Lambda@Edge can be used to rewrite URLs, alter responses based on headers or cookies, or authorize requests based on headers or authorization tokens.

The following shows a Lambda@Edge function added to the default behavior and triggered on every request:

// A Lambda@Edge function added to default behavior of a Distribution
// and triggered on every request
const myFunc = new cloudfront.experimental.EdgeFunction(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_14_X,
  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,
      }
    ],
  },
});

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

// Using a lambda Function instead of an EdgeFunction for stacks in `us-east-`.
const myFunc = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_14_X,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
});

If the stack is not in us-east-1, and you need references from different applications on the same account, you can also set a specific stack ID for each Lambda@Edge.

// Setting stackIds for EdgeFunctions that can be referenced from different applications
// on the same account.
const myFunc1 = new cloudfront.experimental.EdgeFunction(this, 'MyFunction1', {
  runtime: lambda.Runtime.NODEJS_14_X,
  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_14_X,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler2')),
  stackId: 'edge-lambda-stack-id-2',
});

Lambda@Edge functions can also be associated with additional behaviors, either at or after Distribution creation time.

// Associating a Lambda@Edge function with additional behaviors.

declare const myFunc: cloudfront.experimental.EdgeFunction;
// assigning at Distribution creation
declare const myBucket: s3.Bucket;
const myOrigin = new origins.S3Origin(myBucket);
const myDistribution = new cloudfront.Distribution(this, 'myDist', {
  defaultBehavior: { origin: myOrigin },
  additionalBehaviors: {
    'images/*': {
      origin: myOrigin,
      edgeLambdas: [
        {
          functionVersion: myFunc.currentVersion,
          eventType: cloudfront.LambdaEdgeEventType.ORIGIN_REQUEST,
          includeBody: true, // Optional - defaults to false
        },
      ],
    },
  },
});

// assigning after creation
myDistribution.addBehavior('images/*', myOrigin, {
  edgeLambdas: [
    {
      functionVersion: myFunc.currentVersion,
      eventType: cloudfront.LambdaEdgeEventType.VIEWER_RESPONSE,
    },
  ],
});

Adding an existing Lambda@Edge function created in a different stack to a CloudFront distribution.

// Adding an existing Lambda@Edge function created in a different stack
// to a CloudFront distribution.
declare const s3Bucket: s3.Bucket;
const functionVersion = lambda.Version.fromVersionArn(this, 'Version', 'arn:aws:lambda:us-east-1:123456789012:function:functionName:1');

new cloudfront.Distribution(this, 'distro', {
  defaultBehavior: {
    origin: new origins.S3Origin(s3Bucket),
    edgeLambdas: [
      {
        functionVersion,
        eventType: cloudfront.LambdaEdgeEventType.VIEWER_REQUEST,
      },
    ],
  },
});

CloudFront Function

You can also deploy CloudFront functions and add them to a CloudFront distribution.

// Add a cloudfront Function to a Distribution
const cfFunction = new cloudfront.Function(this, 'Function', {
  code: cloudfront.FunctionCode.fromInline('function handler(event) { return event.request }'),
});

declare const s3Bucket: s3.Bucket;
new cloudfront.Distribution(this, 'distro', {
  defaultBehavior: {
    origin: new origins.S3Origin(s3Bucket),
    functionAssociations: [{
      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.

Logging

You can configure CloudFront to create log files that contain detailed information about every user request that CloudFront receives. The logs can go to either an existing bucket, or a bucket will be created for you.

// Configure logging for Distributions

// Simplest form - creates a new bucket and logs to it.
new cloudfront.Distribution(this, 'myDist', {
  defaultBehavior: { origin: new origins.HttpOrigin('www.example.com') },
  enableLogging: true,
});

// You can optionally log to a specific bucket, configure whether cookies are logged, and give the log files a prefix.
new cloudfront.Distribution(this, 'myDist', {
  defaultBehavior: { origin: new origins.HttpOrigin('www.example.com') },
  enableLogging: true, // Optional, this is implied if logBucket is specified
  logBucket: new s3.Bucket(this, 'LogBucket'),
  logFilePrefix: 'distribution-access-logs/',
  logIncludesCookies: true,
});

Importing Distributions

Existing distributions can be imported as well; note that like most imported constructs, an imported distribution cannot be modified. However, it can be used as a reference for other higher-level constructs.

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

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 APINew API
originConfigsdefaultBehavior; use additionalBehaviors if necessary
viewerCertificatecertificate; use domainNames for aliases
errorConfigurationserrorResponses
loggingConfigenableLogging; configure with logBucket logFilePrefix and logIncludesCookies
viewerProtocolPolicyremoved; 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:

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

Behaviors

The modern API makes use of the CloudFront Origins module to easily configure your origin. Replace your origin configuration with the relevant CloudFront Origins class. For example, here's a behavior with an S3 origin:

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

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

Becomes:

declare const sourceBucket: s3.Bucket;

const distribution = new cloudfront.Distribution(this, 'MyCfWebDistribution', {
  defaultBehavior: {
    origin: new origins.S3Origin(sourceBucket) // This class automatically creates an Origin Access Identity
  },
});

In the original API all behaviors are defined in the originConfigs property. The new API is optimized for a single origin and behavior, so the default behavior and additional behaviors will be defined separately.

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

new cloudfront.CloudFrontWebDistribution(this, 'MyCfWebDistribution', {
  originConfigs: [
    {
      s3OriginSource: {
        s3BucketSource: sourceBucket,
        originAccessIdentity: oai,
      },
      behaviors: [ {isDefaultBehavior: true}],
    },
    {
      customOriginSource: {
        domainName: 'MYALIAS',
      },
      behaviors: [{ pathPattern: '/somewhere' }]
    }
  ],
});

Becomes:

declare const sourceBucket: s3.Bucket;

const distribution = new cloudfront.Distribution(this, 'MyCfWebDistribution', {
  defaultBehavior: {
    origin: new origins.S3Origin(sourceBucket) // This class automatically creates an Origin Access Identity
  },
  additionalBehaviors: {
    '/somewhere': {
      origin: new origins.HttpOrigin('MYALIAS'),
    }
  }
});

Certificates

If you are using an ACM certificate, you can pass the certificate directly to the certificate prop. Any aliases used before in the ViewerCertificate class should be passed in to the domainNames prop in the modern API.

import * as acm from '@aws-cdk/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,
});

Becomes:

import * as acm from '@aws-cdk/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,
});

IAM certificates aren't directly supported by the new API, but can be easily configured through escape hatches

declare const sourceBucket: s3.Bucket;
const viewerCertificate = cloudfront.ViewerCertificate.fromIamCertificate('MYIAMROLEIDENTIFIER', {
  aliases: ['MYALIAS'],
});

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

Becomes:

declare const sourceBucket: s3.Bucket;
const distribution = new cloudfront.Distribution(this, 'MyCfWebDistribution', {
  defaultBehavior: {
    origin: new origins.S3Origin(sourceBucket),
  },
  domainNames: ['MYALIAS'],
});

const cfnDistribution = distribution.node.defaultChild as cloudfront.CfnDistribution;

cfnDistribution.addPropertyOverride('ViewerCertificate.IamCertificateId', 'MYIAMROLEIDENTIFIER');
cfnDistribution.addPropertyOverride('ViewerCertificate.SslSupportMethod', 'sni-only');

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 newer Distribution instead, as it has a simpler interface and receives new features faster.

Example usage:

// Using a CloudFrontWebDistribution construct.

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

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:

create a distribution with an default certificate example

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:

create a distribution with an acm certificate example

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:

create a distribution with an iam certificate example

Trusted Key Groups

CloudFront Web Distributions supports validating signed URLs or signed cookies using key groups. When a cache behavior contains trusted key groups, CloudFront requires signed URLs or signed cookies for all requests that match the cache behavior.

Example:

// Using trusted key groups for Cloudfront Web Distributions.
declare const sourceBucket: s3.Bucket;
declare const publicKey: string;
const pubKey = new cloudfront.PublicKey(this, 'MyPubKey', {
  encodedKey: publicKey,
});

const keyGroup = new cloudfront.KeyGroup(this, 'MyKeyGroup', {
  items: [
    pubKey,
  ],
});

new cloudfront.CloudFrontWebDistribution(this, 'AnAmazingWebsiteProbably', {
  originConfigs: [
    {
      s3OriginSource: {
        s3BucketSource: sourceBucket,
      },
      behaviors: [
        {
          isDefaultBehavior: true,
          trustedKeyGroups: [
            keyGroup,
          ],
        },
      ],
    },
  ],
});

Restrictions

CloudFront supports adding restrictions to your distribution.

See Restricting the Geographic Distribution of Your Content in the CloudFront User Guide.

Example:

// Adding restrictions to a Cloudfront Web Distribution.
declare const sourceBucket: s3.Bucket;
new cloudfront.CloudFrontWebDistribution(this, 'MyDistribution', {
  originConfigs: [
    {
      s3OriginSource: {
        s3BucketSource: sourceBucket,
      },
      behaviors : [ {isDefaultBehavior: true}],
    },
  ],
  geoRestriction: cloudfront.GeoRestriction.allowlist('US', 'GB'),
});

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

See Origin Connection Timeout

Example usage:

// Configuring connection behaviors between Cloudfront and your origin
const distribution = new cloudfront.CloudFrontWebDistribution(this, 'MyDistribution', {
  originConfigs: [
    {
      connectionAttempts: 3,
      connectionTimeout: Duration.seconds(10),
      behaviors: [
        {
          isDefaultBehavior: true,
        },
      ],
    },
  ],
});

Origin Fallback

In case the origin source is not available and answers with one of the specified status codes the failover origin source will be used.

// Configuring origin fallback options for the CloudFrontWebDistribution
new cloudfront.CloudFrontWebDistribution(this, 'ADistribution', {
  originConfigs: [
    {
      s3OriginSource: {
        s3BucketSource: s3.Bucket.fromBucketName(this, 'aBucket', 'myoriginbucket'),
        originPath: '/',
        originHeaders: {
          'myHeader': '42',
        },
        originShieldRegion: 'us-west-2',
      },
      failoverS3OriginSource: {
        s3BucketSource: s3.Bucket.fromBucketName(this, 'aBucketFallback', 'myoriginbucketfallback'),
        originPath: '/somewhere',
        originHeaders: {
          'myHeader2': '21',
        },
        originShieldRegion: 'us-east-1',
      },
      failoverCriteriaStatusCodes: [cloudfront.FailoverStatusCode.INTERNAL_SERVER_ERROR],
      behaviors: [
        {
          isDefaultBehavior: true,
        },
      ],
    },
  ],
});

KeyGroup & PublicKey API

You can create a key group to use with CloudFront signed URLs and signed cookies You can add public keys to use with CloudFront features such as signed URLs, signed cookies, and field-level encryption.

The following example command uses OpenSSL to generate an RSA key pair with a length of 2048 bits and save to the file named private_key.pem.

openssl genrsa -out private_key.pem 2048

The resulting file contains both the public and the private key. The following example command extracts the public key from the file named private_key.pem and stores it in public_key.pem.

openssl rsa -pubout -in private_key.pem -out public_key.pem

Note: Don't forget to copy/paste the contents of public_key.pem file including -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY----- lines into encodedKey parameter when creating a PublicKey.

Example:

// Create a key group to use with CloudFront signed URLs and signed cookies.
new cloudfront.KeyGroup(this, 'MyKeyGroup', {
  items: [
    new cloudfront.PublicKey(this, 'MyPublicKey', {
      encodedKey: '...', // contents of public_key.pem file
      // comment: 'Key is expiring on ...',
    }),
  ],
  // comment: 'Key group containing public keys ...',
});

See:

@fern-api/docs-deploy@joelcox22/boilerplate@joelcox22/boilerplate-cdkcicd_spa_websiteinstant-reactaarts-base-infraaws-infrastructurevue-cdk-internal@myhelix-cdk/static-siteadsecure-infra-awssix-foot-six-designs@autoguru/cdksccdk-vuevue-cdk@compassdigital/cafe360-cdk@yippiecloud/cdk-appsync-stack@yippiecloud/cdk-stack-static@yippiecloud/cdk-stack-sveltekit@serverless-toolkit/coredjango-cdk@infinitebrahmanuniverse/nolb-_aws-c@pinecodes/cdk-shared@everything-registry/sub-chunk-101mock-cdk-serverless-website-constructeasycdnplatform-constructspenseur-cdk@cpmech/az-cdk@ef-class/cli@engr-lynx/cdk-service-patterns@jakepartusch/notlify@jakepartusch/notlify-construct@fmtk/cf-static-site@jbt/cli@ikala-cloud/aws-waf-solution@incta/cliumami-analytics-construct@justin8-cdk/static-site@jshaftoe/core@mittonface/resourceswolke-next-cdkwolox-core-infravcs-cdk@neweracode/cdk-static-site@ndlib/ndlib-cdk@lunasec/cli@lunara/liftcicd-spa-website@daysmart/cdk-route-splittingtaimos-cdk-constructsstatic-jekyll-sitespa-websitecrpmro-cdk-patternscloudfront-functions@deathstar/sputnik-infra@deathstar/sputnik-infra-core@csckhw/static-website-construct@devacour/cdk-base@devacour/cdk-webservice@damc-dev/cdk-static-siteserverless-stack-mt-resources@creativepenguin/cdk-static-site@ljagis/aws-constructs@onhand/iac-aws@philcali-cdk/static-website@nona-creative/aws-cdk-s3@nona-creative/cdk-s3-web@planes/cdk-construct@travel.group/cloudfront.authorization@updraft/aws-static-site@tleef/aws-s3-patterns@tsukiy0/aws-cdk-toolbox@serverlessui/construct@qest/aws-cdk-utils@shipula/static@r-token/s3-static-website-construct@softchef/cdk-vue@rnbw/aws-cdk-s3-website@rnbw/aws-cdk-static-website@swymbase/cdk@txp-cms/aws-cdk@taimos/cdk-construct-hosting@seagull/deploy@seagull/deploy-aws@wpkyoto/aws-cdk-cloudfront-s3aarts-cli@xelon/cdk-s3-static-website-constructamplify-category-api@247studios/delivery@abletest/able@aligent/cdk-basic-auth@aligent/cdk-cloudfront-security-headers@aligent/cdk-prerender-proxy@aligent/cdk-prerender-proxy-internal@aligent/cdk-static-hosting@aligent/aws-cdk-static-hosting-stack@aligent/aws-prerender-proxy-stackaws-abgaws-cdk-image-resizer
1.203.0

10 months ago

1.204.0

9 months ago

1.201.0

11 months ago

1.199.0

11 months ago

1.200.0

11 months ago

1.202.0

10 months ago

1.198.1

12 months ago

1.198.0

1 year ago

1.193.0

1 year ago

1.192.0

1 year ago

1.195.0

1 year ago

1.194.0

1 year ago

1.197.0

1 year ago

1.196.0

1 year ago

1.187.0

1 year ago

1.191.0

1 year ago

1.186.0

1 year ago

1.186.1

1 year ago

1.190.0

1 year ago

1.189.0

1 year ago

1.188.0

1 year ago

1.185.0

1 year ago

1.181.0

1 year ago

1.181.1

1 year ago

1.178.0

1 year ago

1.180.0

1 year ago

1.177.0

1 year ago

1.183.0

1 year ago

1.182.0

1 year ago

1.179.0

1 year ago

1.184.0

1 year ago

1.184.1

1 year ago

1.176.0

1 year ago

1.175.0

1 year ago

1.170.0

2 years ago

1.170.1

2 years ago

1.172.0

2 years ago

1.171.0

2 years ago

1.174.0

2 years ago

1.169.0

2 years ago

1.173.0

2 years ago

1.164.0

2 years ago

1.163.0

2 years ago

1.163.2

2 years ago

1.163.1

2 years ago

1.166.1

2 years ago

1.165.0

2 years ago

1.160.0

2 years ago

1.168.0

2 years ago

1.167.0

2 years ago

1.162.0

2 years ago

1.159.0

2 years ago

1.161.0

2 years ago

1.158.0

2 years ago

1.155.0

2 years ago

1.154.0

2 years ago

1.157.0

2 years ago

1.156.0

2 years ago

1.156.1

2 years ago

1.149.0

2 years ago

1.153.0

2 years ago

1.153.1

2 years ago

1.148.0

2 years ago

1.152.0

2 years ago

1.151.0

2 years ago

1.150.0

2 years ago

1.147.0

2 years ago

1.146.0

2 years ago

1.141.0

2 years ago

1.138.2

2 years ago

1.138.1

2 years ago

1.138.0

2 years ago

1.140.0

2 years ago

1.137.0

2 years ago

1.143.0

2 years ago

1.142.0

2 years ago

1.139.0

2 years ago

1.145.0

2 years ago

1.144.0

2 years ago

1.136.0

2 years ago

1.135.0

2 years ago

1.132.0

2 years ago

1.131.0

2 years ago

1.134.0

2 years ago

1.133.0

2 years ago

1.130.0

2 years ago

1.129.0

2 years ago

1.126.0

2 years ago

1.128.0

2 years ago

1.127.0

2 years ago

1.125.0

2 years ago

1.124.0

3 years ago

1.123.0

3 years ago

1.122.0

3 years ago

1.121.0

3 years ago

1.120.0

3 years ago

1.119.0

3 years ago

1.118.0

3 years ago

1.117.0

3 years ago

1.116.0

3 years ago

1.115.0

3 years ago

1.114.0

3 years ago

1.113.0

3 years ago

1.112.0

3 years ago

1.111.0

3 years ago

1.110.1

3 years ago

1.110.0

3 years ago

1.109.0

3 years ago

1.108.0

3 years ago

1.108.1

3 years ago

1.107.0

3 years ago

1.106.1

3 years ago

1.106.0

3 years ago

1.103.0

3 years ago

1.102.0

3 years ago

1.101.0

3 years ago

1.105.0

3 years ago

1.104.0

3 years ago

1.100.0

3 years ago

1.99.0

3 years ago

1.98.0

3 years ago

1.97.0

3 years ago

1.96.0

3 years ago

1.95.2

3 years ago

1.95.1

3 years ago

1.95.0

3 years ago

1.94.1

3 years ago

1.94.0

3 years ago

1.93.0

3 years ago

1.92.0

3 years ago

1.91.0

3 years ago

1.90.1

3 years ago

1.90.0

3 years ago

1.89.0

3 years ago

1.88.0

3 years ago

1.87.1

3 years ago

1.87.0

3 years ago

1.86.0

3 years ago

1.85.0

3 years ago

1.84.0

3 years ago

1.83.0

3 years ago

1.82.0

3 years ago

1.81.0

3 years ago

1.80.0

3 years ago

1.79.0

3 years ago

1.78.0

3 years ago

1.77.0

3 years ago

1.76.0

3 years ago

1.75.0

3 years ago

1.74.0

3 years ago

1.73.0

3 years ago

1.72.0

3 years ago

1.71.0

3 years ago

1.70.0

3 years ago

1.69.0

3 years ago

1.68.0

3 years ago

1.67.0

3 years ago

1.66.0

3 years ago

1.65.0

3 years ago

1.64.1

4 years ago

1.64.0

4 years ago

1.63.0

4 years ago

1.62.0

4 years ago

1.61.1

4 years ago

1.61.0

4 years ago

1.60.0

4 years ago

1.59.0

4 years ago

1.58.0

4 years ago

1.57.0

4 years ago

1.56.0

4 years ago

1.55.0

4 years ago

1.54.0

4 years ago

1.53.0

4 years ago

1.52.0

4 years ago

1.51.0

4 years ago

1.50.0

4 years ago

1.49.1

4 years ago

1.49.0

4 years ago

1.48.0

4 years ago

1.47.1

4 years ago

1.47.0

4 years ago

1.46.0

4 years ago

1.45.0

4 years ago

1.44.0

4 years ago

1.43.0

4 years ago

1.42.1

4 years ago

1.42.0

4 years ago

1.41.0

4 years ago

1.40.0

4 years ago

1.39.0

4 years ago

1.38.0

4 years ago

1.37.0

4 years ago

1.36.1

4 years ago

1.36.0

4 years ago

1.35.0

4 years ago

1.34.1

4 years ago

1.34.0

4 years ago

1.33.1

4 years ago

1.33.0

4 years ago

1.32.2

4 years ago

1.32.1

4 years ago

1.32.0

4 years ago

1.31.0

4 years ago

1.29.0

4 years ago

1.30.0

4 years ago

1.28.0

4 years ago

1.27.0

4 years ago

1.26.0

4 years ago

1.25.0

4 years ago

1.24.0

4 years ago

1.23.0

4 years ago

1.22.0

4 years ago

1.21.1

4 years ago

1.21.0

4 years ago

1.20.0

4 years ago

1.19.0

4 years ago

1.18.0

4 years ago

1.17.1

4 years ago

1.17.0

4 years ago

1.16.3

4 years ago

1.16.2

4 years ago

1.16.1

4 years ago

1.16.0

4 years ago

1.15.0

4 years ago

1.14.0

4 years ago

1.13.1

4 years ago

1.13.0

4 years ago

1.12.0

4 years ago

1.11.0

4 years ago

1.10.1

4 years ago

1.10.0

4 years ago

1.9.0

5 years ago

1.8.0

5 years ago

1.7.0

5 years ago

1.6.1

5 years ago

1.6.0

5 years ago

1.5.0

5 years ago

1.4.0

5 years ago

1.3.0

5 years ago

1.2.0

5 years ago

1.1.0

5 years ago

1.0.0

5 years ago

0.39.0

5 years ago

0.38.0

5 years ago

0.37.0

5 years ago

0.36.2

5 years ago

0.36.1

5 years ago

0.36.0

5 years ago

0.35.0

5 years ago

0.34.0

5 years ago

0.33.0

5 years ago

0.32.0

5 years ago

0.31.0

5 years ago

0.30.0

5 years ago

0.29.0

5 years ago

0.28.0

5 years ago

0.27.0

5 years ago

0.26.0

5 years ago

0.25.3

5 years ago

0.25.2

5 years ago

0.25.1

5 years ago

0.25.0

5 years ago

0.24.1

5 years ago

0.24.0

5 years ago

0.23.0

5 years ago

0.22.0

5 years ago

0.21.0

5 years ago

0.20.0

5 years ago

0.19.0

5 years ago

0.18.1

5 years ago

0.18.0

5 years ago

0.17.0

5 years ago

0.16.0

5 years ago

0.15.2

5 years ago

0.15.1

5 years ago

0.15.0

5 years ago

0.14.1

5 years ago

0.14.0

5 years ago

0.13.0

5 years ago

0.12.0

5 years ago

0.11.0

5 years ago

0.10.0

6 years ago

0.9.2

6 years ago

0.9.1

6 years ago

0.9.0

6 years ago

0.8.2

6 years ago

0.8.1

6 years ago

0.8.0

6 years ago