Skip to content

Instantly share code, notes, and snippets.

@arashatt
Created October 29, 2025 04:34
Show Gist options
  • Save arashatt/2863597ff50fd95b4c5bec854893e8b3 to your computer and use it in GitHub Desktop.
Save arashatt/2863597ff50fd95b4c5bec854893e8b3 to your computer and use it in GitHub Desktop.
cloudflare reverse proxy worker
// Worker: Reverse-proxy to origin on a specific port
const ORIGIN_HOST = "yourserver.com"; // replace with your origin hostname (not the public DNS that clients use)
const ORIGIN_PORT = 8080; // replace with the port your origin listens on (e.g., 8080)
const ORIGIN_PROTO = "https"; // "https" or "http" depending on your origin
addEventListener("fetch", event => {
event.respondWith(handle(event.request));
});
async function handle(request) {
const url = new URL(request.url);
// Build origin URL preserving path + query
const originUrl = `${ORIGIN_PROTO}://${ORIGIN_HOST}:${ORIGIN_PORT}${url.pathname}${url.search}`;
// Build a new headers object copied from the incoming request, but we will remove/replace headers
const newHeaders = new Headers(request.headers);
// Remove headers that can leak client's IP or Cloudflare internals
newHeaders.delete("cf-connecting-ip");
newHeaders.delete("x-forwarded-for");
newHeaders.delete("x-real-ip");
newHeaders.delete("true-client-ip");
// Remove any other headers you don't want forwarded
// newHeaders.delete("some-sensitive-header");
// Ensure Host header is set to your origin host (without the port)
newHeaders.set("Host", ORIGIN_HOST);
// Optionally set X-Forwarded-For to blank or to a fixed value
// (We strip client IPs so origin can't learn the user's IP.)
newHeaders.set("X-Forwarded-For", "");
// Create a new Request object to send to origin
const originReq = new Request(originUrl, {
method: request.method,
headers: newHeaders,
body: request.body === null || request.method === "GET" || request.method === "HEAD"
? null
: request.body,
redirect: "manual",
// If you want to pass credentials or cookies, leave headers as-is; otherwise you can strip cookie headers too
});
// Fetch from the origin
let originResp;
try {
originResp = await fetch(originReq);
} catch (err) {
return new Response("Origin fetch failed: " + err.message, { status: 502 });
}
// Build response headers to return to client, but don't leak origin IP info
const respHeaders = new Headers(originResp.headers);
// Optionally remove server/origin identifying headers
respHeaders.delete("server");
respHeaders.delete("via");
// Remove any other headers that might expose internal IPs or infrastructure:
// respHeaders.delete("x-aws-id"); respHeaders.delete("x-origin-ip"); // example
// Return the response streaming body back to the client
return new Response(originResp.body, {
status: originResp.status,
statusText: originResp.statusText,
headers: respHeaders
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment