Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

リライトルールを設定する

最終更新 Markdown で表示Agent セットアップ

Images 経由で変換するすべての画像に対して、Transform Rules で URL を書き換えられます。

このページでは、次のシナリオの例を扱います。

  • カスタムパスから画像を配信する
  • 既存の URL を Images の変換と互換性がある形に変更する
  • ゾーン上でリクエストされたすべての画像を Images で変換する

ルールを作成するには:

  1. Cloudflare ダッシュボードで Rules Overview ページを開きます。

    Overview を開く ↗
  2. URL Rewrite Rules の横にある 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/ に書き換えます。

Expression Editor のテキスト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/ に書き換えます。

Expression Editor のテキスト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 フィールドは空のままにします。

ゾーン上でリクエストされたすべての画像を Images に通す

この例では、ゾーン上でリクエストされたすべての画像を format=auto オプションで変換します。

(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}")

役に立ちましたか?