# @aws-cdk/aws-cloudfront 中文文档

规范地址：https://npmcn.com/package/%40aws-cdk/aws-cloudfront/

版本：1\.204\.0
npm 元数据更新时间：2023-11-21T10:14:15.438Z
中文译文更新时间：2026-11-07T11:28:29.963Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40aws-cdk/aws-cloudfront
原文对照：https://npmcn.com/package/%40aws-cdk/aws-cloudfront/?lang=original
项目主页：https://github.com/aws/aws-cdk
源码仓库：https://github.com/aws/aws-cdk

弃用说明：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 https://docs\.aws\.amazon\.com/cdk/v2/guide/migrating-v2\.html

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：4.6 MB，45 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>= 14\.15\.0
- 运行依赖：11 个
- peer 依赖：@aws-cdk/aws-certificatemanager 1\.204\.0，@aws-cdk/aws-cloudwatch 1\.204\.0，@aws-cdk/aws-ec2 1\.204\.0，@aws-cdk/aws-iam 1\.204\.0，@aws-cdk/aws-kms 1\.204\.0，@aws-cdk/aws-lambda 1\.204\.0，@aws-cdk/aws-s3 1\.204\.0，@aws-cdk/aws-ssm 1\.204\.0，@aws-cdk/core 1\.204\.0，@aws-cdk/cx-api 1\.204\.0，constructs ^3\.3\.69
- 首次发布：2018-07-31T13:29:45.502Z
- 最新版本发布：2023-06-19T21:09:17.290Z
- 近 30 天下载量：146685（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：288（近 12 个月 0 个）

## 中文简介

AWS: CloudFront 的 CDK 构建库

## 安装

```sh
npm install @aws-cdk/aws-cloudfront
```

也可以使用：`pnpm add @aws-cdk/aws-cloudfront`、`yarn add @aws-cdk/aws-cloudfront`、`bun add @aws-cdk/aws-cloudfront`

## README

# 亚马逊 CloudFront 构造库

* * *

![End-of-Support](https://img.shields.io/badge/End--of--Support-critical.svg?style=for-the-badge)

> AWS CDK v1在2023-06-01上达到了支持结束. 此软件包不再更新,用户应该迁移到 AWS CDK v2.
> 
> 关于如何移徙的更多信息,请参见: [_移动到 AWS CDK v2_ 指南](https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html)。 。 。 .

* * *

Amazon CloudFront是一个网络服务,可以加速您静态和动态的网络内容的发布,例如:.html,.css,.js,以及图像文件等 您的用户。 CloudFront通过一个叫做边缘位置的全球数据中心网络提供你的内容. 当用户要求内容时 您正在和 CloudFront 一起服务, 用户被路由到边缘位置, 提供最小的空闲度, 以便以最好的方式发送内容 可能的表现.

## 分发 API

这个 `Distribution` API 正在建设中,以取代现有的 `CloudFrontWebDistribution` API (英语). 这个 `Distribution` API 优化用于 通常使用 CloudFront 分布(例如,单一来源和行为,很少定制)的病例,同时仍能提供更多 高级使用案例。 API专注于常见使用案例的简单化,以及创建必要的行为和起源的方便方法 更复杂的使用案例.

### 创建分布

CloudFront 分布从一个或多个来源传送您的内容; 一个来源是您存储您的原始版本的位置 内容。 起源可以从S3桶或自定义来源(HTTP服务器)来创建. 定义起源的构造位于 `@aws-cdk/aws-cloudfront-origins` 模块.

每一个发行都有一个默认的行为,适用于该发行的所有请求,以及向主源的路由请求. 对于具有特定 URL 路径模式的源头,可能指定附加行为. 行为允许有多个起源的路由, 控制哪些 HTTP 方法支持,是否要求用户使用 HTTPS,以及哪些查询字符串或 cookie 可以转发到您的出处, 在其它设置中.

#### 从 S3 桶

一个S3桶可以被添加为来源. 如果将桶配置为网站端点, 分发会使用 S3 重定向和 S3 自定义错误 文档.

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

以上将基于下列情况对桶作不同的处理: `IBucket.isWebsite` 是否设定。 如果桶被配置为网站,桶就是 作为 HTTP 源处理,可以使用内置的 S3 重定向和出错页面. 否则,桶作为桶的来源处理 CloudFront的重定向和错误处理将被使用. 在后一种情况下,起源地将建立来源地身份,并允许其接触 下个桶 这可以和不公开的桶一起使用,以要求用户使用 CloudFront 访问您的内容 URL而不是直接的S3 URL.

#### ELBv2 负载平衡器

弹性负载平衡(ELB)v2负载平衡器可用作出产地. 使负载平衡器作为来源,必须公开 无障碍(`internetFacing` ) (中文(简体). 应用程序和网络负荷平衡器都得到支持.

```ts
// Creates a distribution from an ELBv2 load balancer
declare const vpc: ec2.Vpc;
// Create an application load balancer in a VPC. 'internetFacing' must be 'true'
// for CloudFront to access the load balancer and use it as an origin.
const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', {
  vpc,
  internetFacing: true,
});
new cloudfront.Distribution(this, 'myDist', {
  defaultBehavior: { origin: new origins.LoadBalancerV2Origin(lb) },
});
```

#### 从 HTTP 端点

起源也可以从其他HTTP端点创建,考虑到域名,也可以选择其他起源属性.

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

### 域名和证书

当创建发行时,CloudFront为发行指定了域名,例如: `d111111abcdef8.cloudfront.net`; 此值可以 从 `distribution.distributionDomainName`. CloudFront发行使用默认证书(`*.cloudfront.net`)支持HTTPS,通过 默认。 如果您想要使用自己的域名, 如 `www.example.com`,您必须将证书与包含 您的域名,并提供证书中用于分发的一个或多个域名.

证书必须在美国东部(N. Virginia)地区的 AWS 证书管理器服务中存在;证书 可由ACM创建,也可以在其他地方创建并导入ACM. 当使用证书时, 分发会支持 HTTPS 连接 仅来自 SNI 和 TLSv1.2 2021 的最低协议版本,如果 `@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021` 设置了特征标志, 否则则使用 TLSv1.2 2019 .

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

然而,您可以自定义证书的最小协议版本,同时使用 `minimumProtocolVersion` 属性.

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

### 多种行为和起源

每个发行区都有一个默认行为,适用于该发行区的所有请求;可以为一个发行区指定额外行为 给定 URL 路径模式。 行为允许有多个来源的路由,控制HTTP方法支持哪些,是否要求用户 使用 HTTPS, 以及哪些查询字符串或 cookie 来转发您的来源等 .

默认行为属性可以作为发行创建的一部分来调整. 以下示例显示 HTTP 配置 缓存的方法和查看器协议政策.

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

其他行为可以在创建时指定,或在初始创建后添加. 每一个额外的行为都与起源有关, 并允许根据 URL 路径模式定制一组特定资源。 例如,我们可以在 `myWebDistribution` 改为 覆盖所有图像的默认查看器协议政策 .

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

这些行为也可以在发行创建时指定.

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

### 自定义带有缓存策略的缓存密钥和 TTL

您可以使用缓存策略来通过控制值( URL 查询字符串、 HTTP 信头和 cookie) 来提高您的缓存点击率 中包含的缓存密钥,和/或调整缓存中通过时间到启用(TTL)设置保留的项目长度. CloudFront提供了一些预定义的缓存政策,称为被管理的政策,用于常见的用例. 你可以使用这些管理的政策, 或者您可以创建适合您需要的缓存政策. 见 [https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ controlling-the-cache-key.html 互联网档案馆的存檔,存档日期2014-12-12](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html) 更多细节.

```ts
// Using an existing cache policy for a Distribution
declare const bucketOrigin: origins.S3Origin;
new cloudfront.Distribution(this, 'myDistManagedPolicy', {
  defaultBehavior: {
    origin: bucketOrigin,
    cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED,
  },
});
```

```ts
// Creating a custom cache policy for a Distribution -- all parameters optional
declare const bucketOrigin: origins.S3Origin;
const myCachePolicy = new cloudfront.CachePolicy(this, 'myCachePolicy', {
  cachePolicyName: 'MyPolicy',
  comment: 'A default policy',
  defaultTtl: Duration.days(2),
  minTtl: Duration.minutes(1),
  maxTtl: Duration.days(10),
  cookieBehavior: cloudfront.CacheCookieBehavior.all(),
  headerBehavior: cloudfront.CacheHeaderBehavior.allowList('X-CustomHeader'),
  queryStringBehavior: cloudfront.CacheQueryStringBehavior.denyList('username'),
  enableAcceptEncodingGzip: true,
  enableAcceptEncodingBrotli: true,
});
new cloudfront.Distribution(this, 'myDistCustomPolicy', {
  defaultBehavior: {
    origin: bucketOrigin,
    cachePolicy: myCachePolicy,
  },
});
```

### 自定义原产地请求和原产地请求政策

当 CloudFront 向一个来源提出请求时,会包含URL路径,请求正文(如果存在),以及一些标准头. 其它来自取景者请求的信息,如URL查询字符串,HTTP头,和cookie,默认不包含在源请求中. 您可以使用源代码请求策略来控制包含在源代码请求中的信息. CloudFront提供了一些预定义的出处请求政策,称为管理政策,用于常见用例. 你可以使用这些管理的政策, 或者您可以创建您自己的来源 , 申请符合您需要的政策 . 见 [https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-起源-requests.html 互联网档案馆的存檔,存档日期2013-12-21](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html) 更多细节.

```ts
// Using an existing origin request policy for a Distribution
declare const bucketOrigin: origins.S3Origin;
new cloudfront.Distribution(this, 'myDistManagedPolicy', {
  defaultBehavior: {
    origin: bucketOrigin,
    originRequestPolicy: cloudfront.OriginRequestPolicy.CORS_S3_ORIGIN,
  },
});
```

```ts
// Creating a custom origin request policy for a Distribution -- all parameters optional
declare const bucketOrigin: origins.S3Origin;
const myOriginRequestPolicy = new cloudfront.OriginRequestPolicy(this, 'OriginRequestPolicy', {
  originRequestPolicyName: 'MyPolicy',
  comment: 'A default policy',
  cookieBehavior: cloudfront.OriginRequestCookieBehavior.none(),
  headerBehavior: cloudfront.OriginRequestHeaderBehavior.all('CloudFront-Is-Android-Viewer'),
  queryStringBehavior: cloudfront.OriginRequestQueryStringBehavior.allowList('username'),
});

new cloudfront.Distribution(this, 'myDistCustomPolicy', {
  defaultBehavior: {
    origin: bucketOrigin,
    originRequestPolicy: myOriginRequestPolicy,
  },
});
```

### 定制回复信头与回复信头政策

您可以配置 CloudFront 在它发送给取景者(web浏览器或其他客户端)的回复中添加一个或多个 HTTP 头,而无需修改来源或写入任何代码. 要指定 CloudFront 添加到 HTTP 响应中的信头, 您使用响应信头政策 。 CloudFront 添加了信头,无论它是否从缓存中为对象服务,还是必须从来源中取出对象. 如果源响应包含一个响应头政策中的一个或多个头头,政策可以指定CloudFront是使用它从源头收到的头头,还是用政策中的头来覆盖它. 见 [https://docs.aws.amazon.com/AmazonCloudFront/latest/DevelopersGuide/adding-response-headers.html 互联网档案馆的存檔,存档日期2013-12-11](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/adding-response-headers.html)

```ts
// Using an existing managed response headers policy
declare const bucketOrigin: origins.S3Origin;
new cloudfront.Distribution(this, 'myDistManagedPolicy', {
  defaultBehavior: {
    origin: bucketOrigin,
    responseHeadersPolicy: cloudfront.ResponseHeadersPolicy.CORS_ALLOW_ALL_ORIGINS,
  },
});

// Creating a custom response headers policy -- all parameters optional
const myResponseHeadersPolicy = new cloudfront.ResponseHeadersPolicy(this, 'ResponseHeadersPolicy', {
  responseHeadersPolicyName: 'MyPolicy',
  comment: 'A default policy',
  corsBehavior: {
    accessControlAllowCredentials: false,
    accessControlAllowHeaders: ['X-Custom-Header-1', 'X-Custom-Header-2'],
    accessControlAllowMethods: ['GET', 'POST'],
    accessControlAllowOrigins: ['*'],
    accessControlExposeHeaders: ['X-Custom-Header-1', 'X-Custom-Header-2'],
    accessControlMaxAge: Duration.seconds(600),
    originOverride: true,
  },
  customHeadersBehavior: {
    customHeaders: [
      { header: 'X-Amz-Date', value: 'some-value', override: true },
      { header: 'X-Amz-Security-Token', value: 'some-value', override: false },
    ],
  },
  securityHeadersBehavior: {
    contentSecurityPolicy: { contentSecurityPolicy: 'default-src https:;', override: true },
    contentTypeOptions: { override: true },
    frameOptions: { frameOption: cloudfront.HeadersFrameOption.DENY, override: true },
    referrerPolicy: { referrerPolicy: cloudfront.HeadersReferrerPolicy.NO_REFERRER, override: true },
    strictTransportSecurity: { accessControlMaxAge: Duration.seconds(600), includeSubdomains: true, override: true },
    xssProtection: { protection: true, modeBlock: true, reportUri: 'https://example.com/csp-report', override: true },
  },
});
new cloudfront.Distribution(this, 'myDistCustomPolicy', {
  defaultBehavior: {
    origin: bucketOrigin,
    responseHeadersPolicy: myResponseHeadersPolicy,
  },
});
```

### 与信任的关键组验证已签名的 URL 或已签名的 cookie

CloudFront Distruction支持使用关键组验证已签名的URL或已签名的饼干. 当缓存行为包含可信密钥组时, CloudFront 需要签名的 URL 或签名 符合缓存行为的所有请求的 cookie .

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

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

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

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

### 兰布达@ Edge

Lambda@Edge是AWS Lambda的扩展,它是一个允许您执行的计算服务 cloudFront提供的内容自定义的函数。 您可以创建 Node.js 或 Python 在美国东部地区(N. Virginia)的功能,然后在 AWS 中执行 全球范围内更接近于查看器的地段,不提供或管理服务器. Lambda@Edge功能与特定的行为和事件类型相关. 兰布达@ Edge 可用于重写 URL,根据信头或 cookie 更改回复,或授权 基于信头或授权符的请求.

以下显示在默认行为中添加并触发的 Lambda@ Edge 函数 根据每项请求:

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

> **说明:** Lambda@ Edge 函数必须在 `us-east-1` 区域,无论云纹分布和堆放的区域. 为了更容易为 Lambda@Edge 请求功能 `EdgeFunction` 可使用构造. 这个 `EdgeFunction` 构造将自动请求在 `us-east-1`,无论当前堆栈的区域. `EdgeFunction` 具有与 `Function` 并且可以互换地创建和使用. 请注意: `EdgeFunction` 要求 `us-east-1` 区域被取消. 见 [https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html 页面存档备份,存于互联网档案馆](https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html) 更多关于拖带区域.

如果堆栈在 `us-east-1`一个"正常" `lambda.Function` 可用于代替 `EdgeFunction`。 。 。 .

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

如果堆栈不在 `us-east-1`,而你需要从不同的应用程序 引用在同一账户, 您也可以为每个 Lambda@ Edge 设置一个特定的堆栈ID .

```ts
// Setting stackIds for EdgeFunctions that can be referenced from different applications
// on the same account.
const myFunc1 = new cloudfront.experimental.EdgeFunction(this, 'MyFunction1', {
  runtime: lambda.Runtime.NODEJS_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 函数也可以与额外的行为相关, 发行时间或之后.

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

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

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

向 CloudFront 分布器添加不同堆栈中创建的 Lambda@ Edge 函数 .

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

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

### CloudFront 函数

也可以部署 CloudFront 函数并添加到 CloudFront 分布中.

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

declare const s3Bucket: s3.Bucket;
new cloudfront.Distribution(this, 'distro', {
  defaultBehavior: {
    origin: new origins.S3Origin(s3Bucket),
    functionAssociations: [{
      function: cfFunction,
      eventType: cloudfront.FunctionEventType.VIEWER_REQUEST,
    }],
  },
});
```

它会自动生成函数名称并将其部署到 `live` 阶段.

此外,您还可以使用 `FunctionCode.fromFile()` 方法.

### 日志

您可以配置 CloudFront 来创建包含 CloudFront 收到的每个用户请求的详细信息的日志文件 . 木头可以去一个现有的桶,或者为你建立一个桶.

```ts
// Configure logging for Distributions

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

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

### 导入分销

现有的分销也可以进口;请注意,与大多数进口建筑一样,进口分销不能被修改. 然而,它可以作为其他更高级的构造的参考.

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

## 从最初的 CloudFrontWeb 迁移到更新的发行架构

可以将原版的发行量迁移到现代API. 需要进行的修改如下:

### 分布

替换 `new CloudFrontWebDistribution` 与 `new Distribution`某些 配置属性已更改 :

| 旧 API | 新建 API |
| --- | --- |
| `originConfigs` | `defaultBehavior`; 使用 `additionalBehaviors` 必要时 |
| `viewerCertificate` | `certificate`; 使用 `domainNames` 用于别名 |
| `errorConfigurations` | `errorResponses` |
| `loggingConfig` | `enableLogging`; 配置为 `logBucket` `logFilePrefix` 财务报告和审定财务报表 `logIncludesCookies` |
| `viewerProtocolPolicy` | 删除; 以每个行为设定 。 默认更改自 `REDIRECT_TO_HTTPS` 改为 `ALLOW_ALL` |

切换后,您需要为底部保持相同的逻辑ID [分配](https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-cloudfront.CfnDistribution.html) 如果您希望避免删除和娱乐您的分发. 要做到这一点,使用 [逃生舱](https://docs.aws.amazon.com/cdk/v2/guide/cfn_layer.html) 以旧的构造创建的逻辑 ID 来覆盖新发行架构创建的逻辑 ID .

示例

```ts
declare const sourceBucket: s3.Bucket;

const myDistribution = new cloudfront.Distribution(this, 'MyCfWebDistribution', {
  defaultBehavior: {
    origin: new origins.S3Origin(sourceBucket),
  },
});
const cfnDistribution = myDistribution.node.defaultChild as cloudfront.CfnDistribution;
cfnDistribution.overrideLogicalId('MyDistributionCFDistribution3H55TI9Q');
```

### 行为

现代API使用 [云纹起源](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_cloudfront_origins-readme.html) 模块可以轻松配置您的来源。 用相关的 CloudFront Origins 类替换您的源配置 。 例如,这里有一个S3起源的行为:

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

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

成为:

```ts
declare const sourceBucket: s3.Bucket;

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

在最初的 API 中,所有行为都在 `originConfigs` 属性。 新的API被优化为单一起源和行为,因此默认行为和附加行为将被单独定义.

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

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

成为:

```ts
declare const sourceBucket: s3.Bucket;

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

### 证书

如果使用ACM证书,可以直接将证书传递给 `certificate` 道具 (英语). 任何以前使用的别名 `ViewerCertificate` 班级应该传给 `domainNames` 现代API中的道具.

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

成为:

```ts
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 证书不是由新 API 直接支持的,而是很容易通过配置 [逃生舱](https://docs.aws.amazon.com/cdk/v2/guide/cfn_layer.html)

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

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

成为:

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

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

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

### 其他变动

在创建新的发行、行为和来源时,一些默认设置已经在新的API上更改了. 在为迁移做出重大改变后,运行 `cdk diff` 以查看哪些设置已经改变. 如果在迁移过程中不需要更改, 您至少可以使用 [逃生舱](https://docs.aws.amazon.com/cdk/v2/guide/cfn_layer.html) 如果您不能直接更改属性, 则将覆盖 CDK 合成的内容.

## CloudFrontWeb 分配 API

> 这个 `CloudFrontWebDistribution` 构造是用于与 CloudFront 分布式合作的原始构造. 鼓励用户使用更新的 `Distribution` 相反,因为它有一个更简单的接口,并更快地接收到新的特性.

示例用法:

```ts
// Using a CloudFrontWebDistribution construct.

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

### 查看器证书

默认情况下 CloudFront Web Distributions 会用 CloudFront 的默认证书回答 HTTPS 请求, 只包含分布 `domainName` (例如:d111111abcdef8.cloudfront.net). 可以自定义取景者证书属性,提供自定义证书和/或域名别名列表,以适应您的需要.

见 [使用替代域名和 HTTPS](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-https-alternate-domain-names.html) 在 CloudFront 用户指南中.

#### 默认证书

您可以自定义默认证书的别名 。 准备在您的 DNS 区与 CNAME 记录结合使用 .

示例

[创建带有默认证书示例的分布式](https://npmcn.com/package/%40aws-cdk/aws-cloudfront/test/example.default-cert-alias.lit.ts)

#### ACM 证书

您可以用一个存储的 AWS 证书管理器来更改默认证书, 或者 ACM . 这些证书可以由AWS生成,也可以由进口到ACM的另一个CA购买.

更多信息见 [证书管理模块文档](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-certificatemanager-readme.html) 或者说 [将证书导入到 AWS 证书管理器](https://docs.aws.amazon.com/acm/latest/userguide/import-certificate.html) 在AWS证书管理器用户指南中.

示例

[以 acm 证书示例创建分布](https://npmcn.com/package/%40aws-cdk/aws-cloudfront/test/example.acm-cert-alias.lit.ts)

#### IAM 证书

也可以将证书导入到IAM证书商店.

见 [导入 SSL/ TLS 证书](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cnames-and-https-procedures.html#cnames-and-https-uploading-certificates) 在 CloudFront 用户指南中.

示例

[用 iam 证书示例创建发行](https://npmcn.com/package/%40aws-cdk/aws-cloudfront/test/example.iam-cert-alias.lit.ts)

### 信任的关键组

CloudFront Web Distributions支持使用关键组验证已签名的URL或已签名的饼干. 当缓存行为包含可信任的密钥组时,CloudFront需要对所有匹配缓存行为的请求签名的URL或签名的cookie.

示例

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

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

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

### 限制

CloudFront 支持在您的发行中添加限制 .

见 [限制您内容的地理分布](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/georestrictions.html) 在 CloudFront 用户指南中.

示例

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

### CloudFront 和您来源之间的连接行为

CloudFront为您提供了更能控制CloudFront与您来源之间的关联行为. 您现在可以配置 CloudFront 对您的源头的连接尝试数以及每次尝试的源头连接超时 .

见 [原始连接尝试](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#origin-connection-attempts)

见 [来源连接超时](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#origin-connection-timeout)

示例用法:

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

#### 来源倒计时

如果来源不详,用其中一种答案 指定状态代码,将使用故障源源.

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

## 密钥组和公钥 API

您可以用 CloudFront 签名的 URL 和 cookie 创建要使用的密钥组 您可以添加使用 CloudFront 特性的公钥, 如已签名的 URL, 已签名的 cookie, 以及字段加密 .

以下示例命令使用 OpenSSL 生成一个长度为 2048 位的 RSA 密钥对并保存到命名的文件 `private_key.pem`。 。 。 .

```bash
openssl genrsa -out private_key.pem 2048
```

由此产生的文件包含公钥和私钥. 以下示例命令从命名的文件提取公钥 `private_key.pem` 并储存在 `public_key.pem`。 。 。 .

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

注意:不要忘记复制/粘贴 `public_key.pem` 文件包括 `-----BEGIN PUBLIC KEY-----` 财务报告和审定财务报表 `-----END PUBLIC KEY-----` 线入 `encodedKey` 创建时的参数 `PublicKey`。 。 。 .

示例

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

见:

-   [https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html 互联网档案馆的存檔,存档日期2014-12-21](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html)
-   [https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/私人-内容-信任-签名者.html 互联网档案馆的存檔,存档日期2013-12-11](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html)

## 常见问题

### @aws-cdk/aws-cloudfront 是什么？

AWS: CloudFront 的 CDK 构建库注意：该包已被作者标记为弃用——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 https://docs\.aws\.amazon\.com/cdk/v2/guide/migrating-v2\.html

### 如何安装 @aws-cdk/aws-cloudfront？

在项目目录运行 npm install @aws-cdk/aws-cloudfront，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@aws-cdk/aws-certificatemanager（1\.204\.0）、@aws-cdk/aws-cloudwatch（1\.204\.0）、@aws-cdk/aws-ec2（1\.204\.0）、@aws-cdk/aws-iam（1\.204\.0）、@aws-cdk/aws-kms（1\.204\.0）、@aws-cdk/aws-lambda（1\.204\.0）、@aws-cdk/aws-s3（1\.204\.0）、@aws-cdk/aws-ssm（1\.204\.0）、@aws-cdk/core（1\.204\.0）、@aws-cdk/cx-api（1\.204\.0）、constructs（^3\.3\.69）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @aws-cdk/aws-cloudfront 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @aws-cdk/aws-cloudfront 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @aws-cdk/aws-cloudfront 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>= 14\.15\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @aws-cdk/aws-cloudfront 可以商用吗？

@aws-cdk/aws-cloudfront 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @aws-cdk/aws-cloudfront 的下载量有多少？

根据 npm 官方下载统计，@aws-cdk/aws-cloudfront 在 2026/10/07 – 2026/11/05 这 30 天内被下载 146,685 次，日均约 4,890 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @aws-cdk/aws-cloudfront 还在维护吗？

最新版本 1\.204\.0 发布于 2023/06/20（3 年前）；至今共发布 288 个版本，其中过去 12 个月发布了 0 个；首次发布于 2018/07/31。作者已将其标记为弃用，新项目建议寻找替代方案。

