Cloudflare Configuration Guide
1. Create the Cloudflare Worker
Worker Code (JavaScript)
// The primary domain where the Worker is running (e.g., "url.com")
const SOURCE_DOMAIN = "url.com";
// The path prefix to look for on the source domain (e.g., "/hash")
const PATH_PREFIX = "/hash";
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const url = new URL(request.url);
// 1. Check if the request starts with the required path prefix
if (url.pathname.startsWith(PATH_PREFIX)) {
// 2. Extract the part of the path *after* the prefix.
// e.g., if url.pathname is "/hash/some/path", newPathname will be "/some/path"
const newPathname = url.pathname.substring(PATH_PREFIX.length);
// 3. Extract the subdomain from the path prefix (optional, but good for dynamic routing)
// The example uses "hash" for the subdomain, which is hardcoded in the target origin below.
// 4. Construct the new URL for the proxy target (the origin server)
// Target: hash.url.com + /some/path + ?queryparams
const targetUrl = new URL(newPathname, `https://hash.${SOURCE_DOMAIN}`);
targetUrl.search = url.search; // Preserve query parameters
// 5. Create a new request to the target origin, using the original request method and headers
const proxyRequest = new Request(targetUrl.toString(), {
method: request.method,
headers: request.headers,
body: request.body,
redirect: 'follow'
});
// 6. Set the Host header to match the origin server's expected hostname (hash.url.com)
// This is often crucial for the origin server to handle the request correctly.
proxyRequest.headers.set('Host', `hash.${SOURCE_DOMAIN}`);
// 7. Fetch the content from the target URL and return the response
return fetch(proxyRequest);
}
// If the path does not start with /hash, simply fetch the original URL content (for url.com)
return fetch(request);
}2. Deploy the Worker and Set the Route
Route Configuration
Last updated
Was this helpful?