跳转到内容
搜索文档

设置重写规则

最后更新 查看 MarkdownAgent 设置

您可以使用 Transform Rules 为通过 Images 转换的每张图像重写 URL。

本页涵盖以下场景的示例:

  • 从自定义路径提供图像
  • 修改现有 URL 以兼容 Images 中的转换
  • 使用 Images 转换 zone 上请求的每张图像

要创建规则:

  1. 在 Cloudflare 仪表板中,转到 Rules Overview(规则概览) 页面。

    Go to Overview ↗
  2. URL Rewrite Rules(URL 重写规则) 旁边选择 Create rule(创建规则)

开始之前

每条规则在转换请求之前和之后运行。

如果请求的路径与服务器上存储原始图像的路径匹配,这可能导致获取原始图像的请求循环。

要将请求定向到源站服务器,您可以检查 Via 标头中是否包含 image-resizing 字符串:

...and (not (any(http.request.headers["via"][*] contains "image-resizing")))

从自定义路径提供图像

默认情况下,通过 Images 转换图像的请求从 /cdn-cgi/image/ 路径提供。 您可以使用 Transform Rules 重写 URL。

基础版本

Free 和 Pro 计划支持字符串匹配规则(包括通配符操作),无需正则表达式。

此示例让您将 example.com/images 的请求重写为 example.com/cdn-cgi/image/

表达式编辑器中的文本txt
(starts_with(http.request.uri.path, "/images")) and (not (any(http.request.headers["via"][*] contains "image-resizing")))
Path > Rewrite to > Dynamic 中的文本txt
concat("/cdn-cgi/image", substring(http.request.uri.path, 7))

高级版本

有一个支持正则表达式的高级 Transform Rules 版本。

此示例让您将 example.com/images 的请求重写为 example.com/cdn-cgi/image/

表达式编辑器中的文本txt
(http.request.uri.path matches "^/images/.*$") and (not (any(http.request.headers["via"][*] contains "image-resizing")))
Path > Rewrite to > Dynamic 中的文本txt
regex_replace(http.request.uri.path, "^/images/", "/cdn-cgi/image/")

修改现有 URL 以兼容 Images 中的转换

此示例让您重写 URL 参数以兼容 Images:

(http.request.uri matches "^/(.*)\\?width=([0-9]+)&height=([0-9]+)$")
Path > Rewrite to > Dynamic 中的文本txt
regex_replace(
  http.request.uri,
  "^/(.*)\\?width=([0-9]+)&height=([0-9]+)$",
  "/cdn-cgi/image/width=${2},height=${3}/${1}"
)

Query > Rewrite to(重写为) > Static 字段留空。

将 zone 上请求的每张图像通过 Images 转换

此示例让您使用 format=auto 选项转换 zone 上请求的每张图像:

(http.request.uri.path.extension matches "(jpg)|(jpeg)|(png)|(gif)") and (not (any(http.request.headers["via"][*] contains "image-resizing")))
Path > Rewrite to > Dynamic 中的文本txt
regex_replace(http.request.uri.path, "/(.*)", "/cdn-cgi/image/format=auto/${1}")

这篇文档对您有帮助吗?