Skip to content

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

セキュリティヘッダーを設定する

X-XSS-Protection、X-Frame-Options、X-Content-Type-Options などの一般的なセキュリティヘッダーを設定します。

最終更新 Markdown で表示Agent セットアップ
export default {
	async fetch(request) {
		// Define an object with the security headers you want to set.
		// Refer to https://developers.cloudflare.com/rules/snippets/examples/security-headers/#other-common-security-headers for more options.
		const DEFAULT_SECURITY_HEADERS = {
			"X-Content-Type-Options": "nosniff",
			"Referrer-Policy": "strict-origin-when-cross-origin",
			"Cross-Origin-Embedder-Policy": 'require-corp; report-to="default";',
			"Cross-Origin-Opener-Policy": 'same-site; report-to="default";',
			"Cross-Origin-Resource-Policy": "same-site",
		};

		// You can also define headers to be deleted.
		const BLOCKED_HEADERS = [
			"Public-Key-Pins",
			"X-Powered-By",
			"X-AspNet-Version",
		];

		// Receive response from the origin.
		let response = await fetch(request);

		// Create a new Headers object to modify response headers
		let newHeaders = new Headers(response.headers);

		// This sets the headers for HTML responses:
		if (
			newHeaders.has("Content-Type") &&
			!newHeaders.get("Content-Type").includes("text/html")
		) {
			return new Response(response.body, {
				status: response.status,
				statusText: response.statusText,
				headers: newHeaders,
			});
		}

		// Use DEFAULT_SECURITY_HEADERS object defined above to set the new security headers.
		Object.keys(DEFAULT_SECURITY_HEADERS).map((name) => {
			newHeaders.set(name, DEFAULT_SECURITY_HEADERS[name]);
		});

		// Use the BLOCKED_HEADERS object defined above to delete headers you wish to block.
		BLOCKED_HEADERS.forEach((name) => {
			newHeaders.delete(name);
		});

		return new Response(response.body, {
			status: response.status,
			statusText: response.statusText,
			headers: newHeaders,
		});
	},
};

そのほかの一般的なセキュリティヘッダー

  • Content-Security-Policy ヘッダー: 有効にすると、信頼できるドメインとそのすべてのサブドメインからのコンテンツを許可します。 詳細は Content-Security-Policy を参照してください。
"Content-Security-Policy": "default-src 'self' example.com *.example.com",
  • Strict-Transport-Security ヘッダー: サイトが Chrome の HSTS preload リストに追加される可能性があるため、自動では設定しません。
"Strict-Transport-Security" : "max-age=63072000; includeSubDomains; preload",
  • Permissions-Policy ヘッダー: FLoC のオプトアウトなど、ブラウザー機能の使用を許可または拒否します。
"Permissions-Policy": "interest-cohort=()",
  • X-XSS-Protection ヘッダー: XSS 攻撃を検出した場合にページの読み込みを防ぎます。詳細は X-XSS-Protection を参照してください。
"X-XSS-Protection": "0",
  • X-Frame-Options ヘッダー: クリックジャッキング攻撃を防ぎます。X-Frame-Options を参照してください。
"X-Frame-Options": "DENY",

役に立ちましたか?