您可以使用 Transform Rules 为通过 Images 转换的每张图像重写 URL。
本页涵盖以下场景的示例:
- 从自定义路径提供图像
- 修改现有 URL 以兼容 Images 中的转换
- 使用 Images 转换 zone 上请求的每张图像
要创建规则:
-
在 Cloudflare 仪表板中,转到 Rules Overview(规则概览) 页面。
Go to Overview ↗ -
在 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/:
(starts_with(http.request.uri.path, "/images")) and (not (any(http.request.headers["via"][*] contains "image-resizing")))concat("/cdn-cgi/image", substring(http.request.uri.path, 7))有一个支持正则表达式的高级 Transform Rules 版本。
此示例让您将 example.com/images 的请求重写为 example.com/cdn-cgi/image/:
(http.request.uri.path matches "^/images/.*$") and (not (any(http.request.headers["via"][*] contains "image-resizing")))regex_replace(http.request.uri.path, "^/images/", "/cdn-cgi/image/")此示例让您重写 URL 参数以兼容 Images:
(http.request.uri matches "^/(.*)\\?width=([0-9]+)&height=([0-9]+)$")regex_replace(
http.request.uri,
"^/(.*)\\?width=([0-9]+)&height=([0-9]+)$",
"/cdn-cgi/image/width=${2},height=${3}/${1}"
)将 Query > Rewrite to(重写为) > Static 字段留空。
此示例让您使用 format=auto 选项转换 zone 上请求的每张图像:
(http.request.uri.path.extension matches "(jpg)|(jpeg)|(png)|(gif)") and (not (any(http.request.headers["via"][*] contains "image-resizing")))regex_replace(http.request.uri.path, "/(.*)", "/cdn-cgi/image/format=auto/${1}")