跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

高级配置

最后更新 查看 MarkdownAgent 设置

按 URI 模式禁用单次爬网付费

您可能希望对某些页面提供免费访问,而对其他页面收费:

  • 允许免费访问首页、分类页或导航,以帮助爬虫发现付费内容。
  • 排除像登录、搜索或 API 端点 这样不包含收费内容的纯功能性页面。
  • 先在您网站的一小部分 试用单次爬网付费,然后再进行推广。
  • 对促销或存档内容 提供免费访问,而对优质文章收费。

要开始使用,请通过 配置规则 (Configuration Rules) 排除特定的 URI 模式使其不被收费:

  1. 在 Cloudflare 仪表板中前往 Rules(规则)> Overview(概述)。

    前往 Overview(概览) ↗
  2. 选择 Create rule(创建规则)> Configuration Rule(配置规则)。

  3. When incoming requests match(当传入请求匹配时):设置您的 URI 模式。

    • Field(字段):URI Full
    • Operator(运算符):wildcard
    • Value(值):https://*example.com/public/*
  4. 选择 Disable Pay Per Crawl(禁用单次爬网付费)> Add(添加)。

  5. 选择 Deploy(部署)。

模式示例:

  • 免费首页:URI Full 等于 https://example.com/
  • 免费目录:URI Full wildcard https://*example.com/public/*

动态定价

您在 Pay Per Crawl 设置中指定的价格默认适用于整个 zone(站点区域),但您可以通过选择 Enable dynamic pricing(启用动态定价),并让源站 HTTP 响应包含 crawler-price 标头,来实现差异化定价策略。例如:

crawler-price: USD 3.14

当响应中存在 crawler-price 标头时,将使用该标头指定的价格,而不是 zone 的 Pay Per Crawl 设置中的默认价格。

用于动态定价的请求标头

Pay Per Crawl 会向每个源站请求添加 cf-pay-per-crawl 标头。该标头指示当前生效的定价模式,源站可据此决定是否在响应中包含 crawler-price 标头。

cf-pay-per-crawl: protocol=cloudflare, pricing=in-band

目前,protocol 指示符的唯一可能值是 cloudflare。pricing 指示符可以是以下值之一:

  • zone-default:当 zone 未启用 in-band 定价时。
  • in-band:当 zone 已启用动态定价时。
  • bypass:当请求无需付费时(例如,不是 bot)。

使用 Workers 进行动态定价

如果您希望保持源站不变,可以使用 Worker 在响应中包含 crawler-price 标头。在 Worker 中,您可以根据传入请求的属性(包括 Cloudflare 全球网络添加的信息)或内容本身来选择价格。

以下 Worker 脚本实现了一个简单的示例策略:根据请求的 URL 路径选择价格,同时仍利用 Cloudflare Cache:

function getContentPriceUSD(request, response) {
	const requestPath = new URL(request.url).pathname;

	if (requestPath.startsWith("/premium-content/")) {
		return 3.14;
	}

	if (requestPath.startsWith("/free-content/")) {
		return 0.0;
	}

	return null; // Use the default price set in the zone configuration.
}

export default {
	async fetch(request, env, ctx) {
		// Obtain the response first (and allow it to be cached if possible).
		let response = await fetch(request, { cf: { cacheEverything: true } });

		// Indicates the pricing mode in effect ("bypass", "zone-default", "in-band").
		const cfPayPerCrawl = request.headers.get("CF-Pay-Per-Crawl") || "";

		// If in-band pricing is enabled, use the request/response to select a price.
		if (cfPayPerCrawl.match(/\bpricing=in-band\b/)) {
			const contentPrice = getContentPriceUSD(request, response);

			if (contentPrice !== null) {
				// Make the response mutable, to allow setting the price header.
				response = new Response(response.body, response);
				response.headers.set("Crawler-Price", `USD ${contentPrice.toFixed(2)}`);
			}
		}
		return response;
	}
};

附加资源

这篇文档对您有帮助吗?