Cloudflare Configuration Guide
1. Create the Cloudflare Worker
Worker Code (JavaScript)
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
Route Configuration
Last updated
Was this helpful?