Skip to content

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

オリジンへのアクセスを制御する

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

リサイズ済み画像を配信しつつ、元画像へのアクセスは渡せないようにできます。画像はゾーン外の別サーバーでホストでき、画像の本当のソースは完全に隠せます。オリジンサーバーは、訪問者に意識させずに、元画像の開示に認証を要求できます。リサイズパラメーターを操作できないようにすることで、フルサイズ画像へのアクセスを防げます。

これらの動作はすべてカスタマイズできます。処理は Cloudflare Worker のエッジで動く スクリプトのカスタムコードで行います。

export default {
	async fetch(request, env, ctx) {
		// Here you can compute arbitrary imageURL and
		// resizingOptions from any request data ...
		return fetch(imageURL, { cf: { image: resizingOptions } });
	},
};

このコードはリクエストごとに実行されますが、ソースコードはウェブサイトの訪問者からは見えません。そのため、セキュリティチェックを実行したり、制御された方法で画像にアクセスするために必要なシークレットを含めたりできます。

以下の例は提案にすぎず、厳密に従う必要はありません。画像 URL とリサイズオプションは、ほかの方法でも計算できます。

画像サーバーを隠す

export default {
	async fetch(request, env, ctx) {
		const resizingOptions = {
			/* resizing options will be demonstrated in the next example */
		};

		const hiddenImageOrigin = "https://secret.example.com/hidden-directory";
		const requestURL = new URL(request.url);
		// Append the request path such as "/assets/image1.jpg" to the hiddenImageOrigin.
		// You could also process the path to add or remove directories, modify filenames, etc.
		const imageURL = hiddenImageOrigin + requestURL.pathname;
		// This will fetch image from the given URL, but to the website's visitors this
		// will appear as a response to the original request. Visitor’s browser will
		// not see this URL.
		return fetch(imageURL, { cf: { image: resizingOptions } });
	},
};

フルサイズ画像へのアクセスを防ぐ

元画像の URL を保護したうえで、許可する画像サイズを検証することもできます。

export default {
  async fetch(request, env, ctx) {
  const imageURL =// detail omitted in this example, see the previous example

  const requestURL = new URL(request.url)
  const width = parseInt(requestURL.searchParams.get("width"), 10);
  const resizingOptions = { width }
  // If someone tries to manipulate your image URLs to reveal higher-resolution images,
  // you can catch that and refuse to serve the request (or enforce a smaller size, etc.)
  if (resizingOptions.width > 1000) {
    return new Response("We don't allow viewing images larger than 1000 pixels wide", { status: 400 })
  }
  return fetch(imageURL, {cf:{image:resizingOptions}})
},};

URL に画像サイズを含めない

URL に実際のピクセルサイズを含める必要はありません。サイズは Worker スクリプトに埋め込み、別の方法で選べます。たとえば、URL 内のプリセット名で指定します。

export default {
	async fetch(request, env, ctx) {
		const requestURL = new URL(request.url);
		const resizingOptions = {};

		// The regex selects the first path component after the "images"
		// prefix, and the rest of the path (e.g. "/images/first/rest")
		const match = requestURL.pathname.match(/images\/([^/]+)\/(.+)/);

		// You can require the first path component to be one of the
		// predefined sizes only, and set actual dimensions accordingly.
		switch (match && match[1]) {
			case "small":
				resizingOptions.width = 300;
				break;
			case "medium":
				resizingOptions.width = 600;
				break;
			case "large":
				resizingOptions.width = 900;
				break;
			default:
				throw Error("invalid size");
		}

		// The remainder of the path may be used to locate the original
		// image, e.g. here "/images/small/image1.jpg" would map to
		// "https://storage.example.com/bucket/image1.jpg" resized to 300px.
		const imageURL = "https://storage.example.com/bucket/" + match[2];
		return fetch(imageURL, { cf: { image: resizingOptions } });
	},
};

認証付きオリジン

Cloudflare の画像変換は、パフォーマンス向上のためにリサイズ済み画像をキャッシュします。アクセス制限のある画像のリサイズは、訪問者ごとにカスタマイズした画像の共有が安全ではないため、一般的には推奨しません。ただし、そのような画像を公開キャッシュに置くことに同意する場合、Cloudflare は Workers 経由のリサイズに対応します。現時点では、認証付きの AWS、Azure、Google Cloud、SecureAuth のオリジンと、Cloudflare Access の背後にあるオリジンで利用できます。

// generate signed headers (application specific)
const signedHeaders = generatedSignedHeaders();

fetch(private_url, {
	headers: signedHeaders,
	cf: {
		image: {
			format: "auto",
			"origin-auth": "share-publicly",
		},
	},
});

このコードを使うと、次のヘッダーがオリジンに渡され、リクエストを成功させられます。

  • Authorization
  • Cookie
  • x-amz-content-sha256
  • x-amz-date
  • x-ms-date
  • x-ms-version
  • x-sa-date
  • cf-access-client-id
  • cf-access-client-secret

詳しくは、次を参照してください。

役に立ちましたか?