跳转到内容
搜索文档

设置安全响应头

设置常见安全响应头,例如 X-XSS-Protection、X-Frame-Options 和 X-Content-Type-Options。

最后更新 查看 MarkdownAgent 设置
export default {
	async fetch(request) {
		// Define an object with the security headers you want to set.
		// See 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 响应头:防止点击劫持(click-jacking)攻击。请参阅 X-Frame-Options
"X-Frame-Options": "DENY",

这篇文档对您有帮助吗?