Cloudflare Configuration Guide
This Documentation is based on the following official Cloudflare Docs: URL forwarding
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)
Log in to your Cloudflare Dashboard and navigate to Workers & Pages.
Click Create Application and then Create Worker. Give your worker a meaningful name (e.g.,
reverse-proxy-hash).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
Navigate back to your Workers & Pages dashboard and select your new Worker.
Go to the Triggers tab.
In the Routes section, click Add route.
Configure the route:
Route:
url.com/hash(Replaceurl.comwith your actual domain).Worker: Select the Worker you just created (e.g.,
reverse-proxy-hash).
Click Add route.
Last updated
Was this helpful?