How to Use a Cloudflare Worker to trigger RL rule and Rewrite URLs

The following example shows a simple Cloudflare Worker script that checks if a rate-limiting rule has been triggered. If so, it rewrites the request URL to serve content from a fallback page.

Cloudflare Worker: Check Rate Limiting and Fetch from Different URL/Path

You can use Cloudflare Workers' built-in Rate Limiting API to detect if a user exceeds your defined rate limits and, if so, serve content from a different URL or path. Here’s how you can implement this pattern:

In your wrangler.toml, define a rate limiting binding. For example:


  [[unsafe.bindings]]
name = "MY_RATE_LIMITER"
type = "ratelimit"
namespace_id = "1001"  # Replace with your real namespace ID
simple = { limit = 5, period = 60 }  # 5 requests per 60 seconds

Below is a practical Worker script. If the rate limit is triggered, it fetches content from a different URL and/or path, returning that to the user:


  export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    // Your rate limit key; adjust as needed (e.g., by IP, path)
    const key = `${request.headers.get("cf-connecting-ip")}:${url.pathname}`;

    // Check rate limit
    const { success } = await env.MY_RATE_LIMITER.limit({ key });

    if (!success) {
      // Rate limit exceeded: fetch from alternate URL/path
      const fallbackUrl = "https://www.tpimenta.xyz/ratelimiting/fallback-content.html"; // Replace as needed
      // Optionally, rewrite just the path (same host):
      // url.pathname = "/fallback-path"; return fetch(url, request);

      // Fetch and return fallback content
      return fetch(fallbackUrl, request);
    }

    // Normal flow: forward original request
    return fetch(request);
  }
}

Request Counter and Data Fetcher

Requests from this user: