PAYATHON 2026

文件名包含单引号时,如何使 CloudFront 路径的缓存失效?

排障赵师傅

不必禁止文件名中的单引号。保留路径中的 /,对每个路径段分别调用 encodeURIComponent(),再将 ' 替换为 %27,最后把完整路径传给 Paths.Items。

示例代码中能确定的问题是:URLSearchParams.toString() 生成的是以 text= 开头的查询字符串,而 CloudFront API 要求失效路径以 / 开头。其他编码尝试为什么失败,仅凭这条 InvalidArgument 还无法确定,也不能都归因于单引号。CloudFront 路径要求

为什么原来的编码方式有问题

以这个文件路径为例:

/Folder/John's report.json
处理方式结果问题
encodeURI(filePath)/Folder/John's%20report.json保留了 /,也保留了 '
encodeURIComponent(filePath)%2FFolder%2FJohn's%20report.json把路径分隔符 / 也编码了,失去了必需的开头 /
new URLSearchParams({ text: filePath }).toString()text=%2FFolder%2FJohn%27s+report.json生成了键值对形式的查询字符串,并把空格转换成 +

encodeURI() 和 encodeURIComponent() 都会保留单引号,这是 JavaScript 的既定行为。URLSearchParams 使用 application/x-www-form-urlencoded 序列化规则,虽然会把单引号编码为 %27,但生成的是查询参数,不能直接作为 CloudFront 的失效路径。ECMAScript URI 编码规范、URL 序列化规范

按路径段编码后提交

下面的 TypeScript 示例接收未经 URL 编码的文件路径:

import { randomUUID } from 'node:crypto';
import {
  CloudFrontClient,
  CreateInvalidationCommand,
} from '@aws-sdk/client-cloudfront';

const cloudfrontClient = new CloudFrontClient({
  region: 'us-east-1',
});

function encodeInvalidationPath(filePath: string): string {
  const path = filePath.startsWith('/') ? filePath : `/${filePath}`;

  return path
    .split('/')
    .map((segment) =>
      encodeURIComponent(segment).replace(/'/g, '%27')
    )
    .join('/');
}

export async function invalidateCacheForFile(
  distributionId: string,
  filePath: string
) {
  const encodedPath = encodeInvalidationPath(filePath);

  return cloudfrontClient.send(
    new CreateInvalidationCommand({
      DistributionId: distributionId,
      InvalidationBatch: {
        Paths: {
          Quantity: 1,
          Items: [encodedPath],
        },
        CallerReference: randomUUID(),
      },
    })
  );
}

例如:

encodeInvalidationPath("/Folder/John's report.json");
// "/Folder/John%27s%20report.json"

函数先用 / 拆分路径,逐段编码并替换单引号,再用 / 拼回完整路径。这样保留了目录结构,传入 Items 的字符串以 / 开头,不带 text=,空格也会编码为 %20。

示例用 CallerReference 为每次新调用生成唯一值。如果业务层需要重试同一批失效请求,应沿用原来的 CallerReference,以便 CloudFront 按重复请求处理。CreateInvalidation API

与 encodeURI() 后替换单引号有什么区别

如果路径只包含本题中的目录、空格和单引号,也可以写成:

const encodedPath = encodeURI(filePath).replace(/'/g, '%27');

前提是 filePath 已以 / 开头,且未经编码。

逐段使用 encodeURIComponent() 更适合处理原始文件名。例如,文件名中的 ? 或 # 需要按文件名字符编码;encodeURI() 会保留这两个字符,容易让它们被理解为查询字符串或片段的标记。ECMAScript URI 编码规范

提交前还要核对什么

编码后的路径必须对应实际访问并缓存的 CloudFront URL。AWS 要求对非 ASCII 字符和不安全字符进行 URL 编码,也提醒不要随意编码其他字符,否则可能无法清除目标缓存。请求被接受,并不代表命中了预期缓存;' 与 %27 也不能在所有场景下互换。CloudFront 编码说明

排查时检查以下几项:

  • 传给上述函数的应是原始路径。如果已经包含 %27、%20,再次编码就会得到 %2527、%2520。
  • 使用相对于 CloudFront distribution 的访问路径,例如 /Folder/file.json,不要传完整 URL、s3://... 或带 bucket 名称的路径。
  • 如果缓存按查询字符串区分版本,或配置了 URI 重写,还需要处理对应的缓存路径;上述函数只负责文件路径编码。
  • 提交成功后,等待失效状态变为 Completed 再验证结果。失效状态说明

日志中的 httpStatusCode: 400 和 '$fault': 'client' 表明 AWS 拒绝了请求参数,外层的 Internal server error 文案不改变这一点。排查应从最终传入 Paths.Items 的字符串入手。这条通用错误不足以说明 S3 文件名不能包含单引号。

备注:内容仅供参考。