Vary HTTP レスポンスヘッダーは、同じリソースでもリクエストヘッダーに応じてオリジンが別バージョンを返せることを Cloudflare に伝えます。画像では、対応ブラウザーには WebP や AVIF などの新しい形式を返し、それ以外には JPEG や PNG を返し続けられます。
Cloudflare は画像のバリアント付きレスポンスを受け取ると、バリアントごとに別々にキャッシュします。同じ画像形式の設定のブラウザーからの後続リクエストは、オリジンへ問い合わせずキャッシュから直接返します。
Vary for Images は、各リクエストの Accept ヘッダーを解析してブラウザーが対応する画像形式を判断し、一致するキャッシュ済みバリアントを返します。
Vary for Images は、Pro、Business、Enterprise のお客様が利用できます。
| Free | Pro | Business | Enterprise | |
|---|---|---|---|---|
| 提供状況 | なし | あり | あり | あり |
オリジンサーバーが 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 でバリアントルールを作成して有効にします。次の例では、.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 のファイル拡張子はパスに含め、クエリ文字列には置かないでください。たとえば
https://example.com/image.jpgは使えますが、https://example.com/index.php?file=image.jpgは使えません。 - HTTP クライアントが
Acceptヘッダーを送らない場合、またはAccept: */*ヘッダーを送る場合、オリジンは URL のファイル拡張子と一致する画像タイプを返す必要があります。そうでないと、HTTP レスポンスヘッダーにCF-Cache-Status: BYPASSと表示されます。