跳转到内容
搜索文档

添加自定义 HTTP 标头

最后更新 查看 MarkdownAgent 设置

更高级的 HTTP 标头自定义可通过 Cloudflare Workers 无服务器函数实现。

若尚未部署 Worker,请从我们的 教程 开始。就本教程而言,在返回本页之前,请完成步骤一(注册 Workers 账户)到步骤四(生成新项目)。

继续之前,请确保 Cloudflare Pages 项目已连接到 自定义域

编写 Workers 函数

Workers 函数使用 JavaScript 编写。当 Worker 向 Cloudflare Pages 应用发出请求时,将收到响应。Worker 收到的响应是不可变的,意味着无法更改。要添加、删除或修改标头,需克隆响应并在新的 Response 实例上修改标头。将带有所需标头更改的新响应返回给浏览器。示例如下:

Setting custom headers with a Workers functionjs
export default {
	async fetch(request) {
		// This proxies your Pages application under the condition that your Worker script is deployed on the same custom domain as your Pages project
		const response = await fetch(request);

		// Clone the response so that it is no longer immutable
		const newResponse = new Response(response.body, response);

		// Add a custom header with a value
		newResponse.headers.append(
			"x-workers-hello",
			"Hello from Cloudflare Workers",
		);

		// Delete headers
		newResponse.headers.delete("x-header-to-delete");
		newResponse.headers.delete("x-header2-to-delete");

		// Adjust the value for an existing header
		newResponse.headers.set("x-header-to-change", "NewValue");

		return newResponse;
	},
};

在仪表板中部署 Workers 函数

开始部署 Workers 函数的最简单方式是在浏览器中输入 workers.new。登录账户后将自动进入 Workers & Pages 仪表板。在 Workers & Pages 仪表板中编写函数,或使用 Workers 文档中的示例

脚本就绪后选择 Save and Deploy(保存并部署),并在域 zone 设置中配置 路由

例如,此处有一个 Workers 脚本,可复制粘贴到 Workers 仪表板,在请求访问 Pages URL 时设置常见安全标头,如 X-XSS-Protection、X-Frame-Options、X-Content-Type-Options、Strict-Transport-Security、Content-Security-Policy (CSP) 等。

使用 CLI 部署 Workers 函数

若希望跳过自行编写此文件,可使用 custom-headers-example 模板,通过 Wrangler(Workers CLI 工具)生成新的 Workers 函数。

Generating a serverless function with wranglersh
git clone https://github.com/cloudflare/custom-headers-example
cd custom-headers-example
npm install

要在 Pages 应用旁运行 Workers 函数,请将其部署到与 Pages 应用相同的自定义域。为此,使用账户和 zone 详情更新项目中的 Wrangler 文件:

{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "custom-headers-example",
	"account_id": "FILL-IN-YOUR-ACCOUNT-ID",
	"workers_dev": false,
	"route": "FILL-IN-YOUR-WEBSITE.com/*",
	"zone_id": "FILL-IN-YOUR-ZONE-ID"
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "custom-headers-example"
account_id = "FILL-IN-YOUR-ACCOUNT-ID"
workers_dev = false
route = "FILL-IN-YOUR-WEBSITE.com/*"
zone_id = "FILL-IN-YOUR-ZONE-ID"

若不知道如何查找 Account ID 和 Zone ID,请参阅 我们的指南

配置 Wrangler 配置文件 后,在终端运行 npx wrangler deploy 部署 Worker:

npx wrangler deploy

部署 Worker 后,所需的 HTTP 标头调整将生效。Worker 部署期间,你应继续正常看到 Pages 应用的内容。

这篇文档对您有帮助吗?