Vary HTTP 响应标头告诉 Cloudflare,源站可以根据请求标头提供同一资源的不同版本。对于图片,这允许您的源站向支持现代格式的浏览器提供 WebP 或 AVIF 等格式,同时继续向其他浏览器提供 JPEG 或 PNG。
当 Cloudflare 收到带有图片变体的响应时,它会分别缓存每个变体。来自具有相同图片格式偏好的浏览器的后续请求直接从缓存提供,无需联系您的源站。
Vary for Images 通过解析每个请求中的 Accept 标头来确定浏览器支持哪种图片格式,然后提供匹配的缓存变体。
Vary for images 适用于 Pro、Business 和 Enterprise 客户。
| Free | Pro | Business | Enterprise | |
|---|---|---|---|---|
Availability | No | Yes | Yes | Yes |
如果源站服务器发送 Vary: Accept 响应标头,您可以在以下文件扩展名上使用 vary for images。如果源站服务器发送 Vary: Accept 但不提供设置的变体,则不会缓存响应,并在响应标头中的缓存状态显示 BYPASS。此外,必须配置源站为每个扩展名提供的变体类型列表,以便 Cloudflare 决定提供哪个变体而无需联系源站服务器。
启用 vary 的文件扩展名
- .avif
- .bmp
- .gif
- .jpg
- .jpeg
- .jp2
- .png
- .tif
- .tiff
- .webp
Vary for Images 通过 Cloudflare API 创建 variants 规则来启用。在以下示例中,了解如何为 .jpeg 和 .jpg 扩展名提供 JPEG、WebP 和 AVIF 变体。
Required API token permissions
At least one of the following token permissions is required:Zone Settings WriteZone Write
curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/cache/variants" \
--request PATCH \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--json '{
"value": {
"jpeg": [
"image/webp",
"image/avif"
],
"jpg": [
"image/webp",
"image/avif"
]
}
}'Required API token permissions
At least one of the following token permissions is required:Zone Settings WriteZone Write
curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/cache/variants" \
--request PATCH \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--json '{
"value": {
"jpeg": [
"image/webp"
],
"jpg": [
"image/webp"
]
}
}'Required API token permissions
At least one of the following token permissions is required:Zone Settings WriteZone Write
curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/cache/variants" \
--request DELETE \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"Required API token permissions
At least one of the following token permissions is required:Zone Settings WriteZone Settings ReadZone ReadZone Write
curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/cache/variants" \
--request GET \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"要了解更多关于清除变体图片的信息,请参阅清除变体图片。
- 要使 Vary for images 生效,您的图片 URL 必须在路径中包含文件扩展名,而不是在查询字符串中。例如 URL
https://example.com/image.jpg兼容,但https://example.com/index.php?file=image.jpg不兼容。 - 当 HTTP 客户端不发送
Accept标头,或发送Accept: */*标头时,您的源站必须返回与 URL 中文件扩展名匹配的图片类型。否则,您将在 HTTP 响应标头中看到CF-Cache-Status: BYPASS。