refactor: improve n8n routing logic with prefix handling and automated redirects
Browse files- health-server.js +25 -5
health-server.js
CHANGED
|
@@ -300,19 +300,35 @@ const server = http.createServer(async (req, res) => {
|
|
| 300 |
);
|
| 301 |
}
|
| 302 |
|
| 303 |
-
//
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
}
|
|
|
|
|
|
|
|
|
|
| 309 |
if (!proxyPath.startsWith("/")) proxyPath = "/" + proxyPath;
|
| 310 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
const proxyHeaders = {
|
| 312 |
...req.headers,
|
| 313 |
host: `127.0.0.1:${TARGET_PORT}`,
|
| 314 |
"x-forwarded-for": req.socket.remoteAddress,
|
| 315 |
"x-forwarded-proto": "https",
|
|
|
|
| 316 |
};
|
| 317 |
|
| 318 |
const proxyReq = http.request(
|
|
@@ -324,6 +340,10 @@ const server = http.createServer(async (req, res) => {
|
|
| 324 |
headers: proxyHeaders,
|
| 325 |
},
|
| 326 |
(proxyRes) => {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
res.writeHead(proxyRes.statusCode, proxyRes.headers);
|
| 328 |
proxyRes.pipe(res);
|
| 329 |
},
|
|
|
|
| 300 |
);
|
| 301 |
}
|
| 302 |
|
| 303 |
+
// 1. Redirect root /app to /app/ (trailing slash)
|
| 304 |
+
if (pathname === APP_BASE) {
|
| 305 |
+
res.writeHead(301, { Location: APP_BASE + "/" });
|
| 306 |
+
return res.end();
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
// 2. Confine n8n to /app subpath
|
| 310 |
+
// If it's not a dashboard path and doesn't start with /app, redirect to /app/
|
| 311 |
+
if (!pathname.startsWith(APP_BASE + "/")) {
|
| 312 |
+
res.writeHead(302, { Location: APP_BASE + "/" });
|
| 313 |
+
return res.end();
|
| 314 |
}
|
| 315 |
+
|
| 316 |
+
// 3. Proxy to n8n (strip /app prefix)
|
| 317 |
+
let proxyPath = pathname.substring(APP_BASE.length);
|
| 318 |
if (!proxyPath.startsWith("/")) proxyPath = "/" + proxyPath;
|
| 319 |
|
| 320 |
+
// Handle n8n's common 404 on root / by redirecting to workflows
|
| 321 |
+
if (proxyPath === "/" && req.method === "GET") {
|
| 322 |
+
res.writeHead(302, { Location: APP_BASE + "/home/workflows" });
|
| 323 |
+
return res.end();
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
const proxyHeaders = {
|
| 327 |
...req.headers,
|
| 328 |
host: `127.0.0.1:${TARGET_PORT}`,
|
| 329 |
"x-forwarded-for": req.socket.remoteAddress,
|
| 330 |
"x-forwarded-proto": "https",
|
| 331 |
+
"x-forwarded-prefix": APP_BASE,
|
| 332 |
};
|
| 333 |
|
| 334 |
const proxyReq = http.request(
|
|
|
|
| 340 |
headers: proxyHeaders,
|
| 341 |
},
|
| 342 |
(proxyRes) => {
|
| 343 |
+
// Rewrite Location header for redirects
|
| 344 |
+
if (proxyRes.headers.location && proxyRes.headers.location.startsWith("/")) {
|
| 345 |
+
proxyRes.headers.location = APP_BASE + proxyRes.headers.location;
|
| 346 |
+
}
|
| 347 |
res.writeHead(proxyRes.statusCode, proxyRes.headers);
|
| 348 |
proxyRes.pipe(res);
|
| 349 |
},
|