Skip to content

Instantly share code, notes, and snippets.

@goenning
Created April 17, 2026 14:28
Show Gist options
  • Select an option

  • Save goenning/3c5a94f9e61b66e3272f69ecceecbf11 to your computer and use it in GitHub Desktop.

Select an option

Save goenning/3c5a94f9e61b66e3272f69ecceecbf11 to your computer and use it in GitHub Desktop.
const HELP_HOST = "seogets.hc.ferndesk.com";
const PROXY_PREFIX = "/help";
export default async function middleware(request: Request): Promise<Response> {
const originalUrl = new URL(request.url);
const upstreamUrl = new URL(originalUrl.toString());
upstreamUrl.hostname = HELP_HOST;
if (upstreamUrl.pathname === PROXY_PREFIX || upstreamUrl.pathname === `${PROXY_PREFIX}/`) {
upstreamUrl.pathname = "/";
} else if (upstreamUrl.pathname.startsWith(`${PROXY_PREFIX}/`)) {
let upstreamPath = upstreamUrl.pathname.slice(PROXY_PREFIX.length) || "/";
if (upstreamPath.endsWith("/") && upstreamPath !== "/") {
upstreamPath = upstreamPath.slice(0, -1);
}
upstreamUrl.pathname = upstreamPath;
}
const proxyRequest = new Request(upstreamUrl.toString(), request);
// CRITICAL: Needed to resolve requests correctly
proxyRequest.headers.set("X-Ferndesk-Base-Path", PROXY_PREFIX);
proxyRequest.headers.set("X-Forwarded-Host", originalUrl.host);
proxyRequest.headers.set("X-Ferndesk-Original-Host", originalUrl.host);
return fetch(proxyRequest);
}
export const config = {
matcher: ["/help", "/help/", "/help/(.*)", "/_ferndesk/(.*)"],
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment