Cloudflare Configuration Guide

This Documentation is based on the following official Cloudflare Docs: URL forwardingarrow-up-right


1. Create the Cloudflare Worker

You will write a simple JavaScript function to intercept the request, modify the URL, and fetch the content from the new location.

Worker Code (JavaScript)

  1. Log in to your Cloudflare Dashboard and navigate to Workers & Pages.

  2. Click Create Application and then Create Worker. Give your worker a meaningful name (e.g., reverse-proxy-hash).

  3. Replace the default code with the following script:

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    const hash = "{{your-subdomain-hash}}";
    const domain = "{{your-domain}}";
    const trackingDomain = `${hash}.${domain}`;

    if (url.pathname.startsWith(`/${hash}`)) {
      // 1. Define the destination
      const targetUrl = new URL(request.url);
      targetUrl.hostname = trackingDomain;
      // 2. Strip the '/{{hash}}' prefix so the second server sees the request as root '/'
      targetUrl.pathname = url.pathname.replace(`/${hash}`, "");
      if (targetUrl.pathname === "") targetUrl.pathname = "/";
      // 3. Create a new request to modify headers
      const modifiedRequest = new Request(targetUrl, request);
      // 4. CRITICAL: Tell the second server it's receiving a request for the subdomain
      modifiedRequest.headers.set("Host", trackingDomain);
      return fetch(modifiedRequest);
    }
    return fetch(request);
  },
};

2. Deploy the Worker and Set the Route

Once you have saved and deployed the worker code, you need to tell Cloudflare when to execute it. This is done by setting a Route.

Route Configuration

  1. Navigate back to your Workers & Pages dashboard and select your new Worker.

  2. Go to the Triggers tab.

  3. In the Routes section, click Add route.

  4. Configure the route:

    • Route: url.com/hash (Replace url.com with your actual domain).

    • Worker: Select the Worker you just created (e.g., reverse-proxy-hash).

  5. Click Add route.

triangle-exclamation

Last updated

Was this helpful?