From a065ddc6f25954a2576bbd4629d30faaad094456 Mon Sep 17 00:00:00 2001 From: Tim DiLauro Date: Mon, 6 Nov 2023 12:01:10 -0500 Subject: [PATCH] Fix webpack dev-server handling of relative links. --- webpack.dev-server.config.js | 47 ++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/webpack.dev-server.config.js b/webpack.dev-server.config.js index 7b45972d..554c2b63 100644 --- a/webpack.dev-server.config.js +++ b/webpack.dev-server.config.js @@ -62,6 +62,40 @@ module.exports = (env) => { const rewriteLocationHeader = (res, req) => { const location = res.getHeader("location"); + if (!location) { + return; + } + // Use the referer as the base URL, if location is relative. + const referer = req.headers.referer; + const locationUrl = new URL(location, referer); + + if (locationUrl.host !== backendUrl.host) { + return; + } + + const requestHost = req.headers.host; + + if (!requestHost) { + return; + } + + locationUrl.protocol = "http"; + locationUrl.host = requestHost; + + res.setHeader("location", locationUrl.href); + }; + + /** + * Rewrite a location header (as received in a 3xx response). This changes back-end URLs to + * point to the local server instead. The CM may redirect to a URL that contains a "redirect" + * parameter that contains another URL. The "redirect" parameter is also rewritten. + * + * @param res The response. + * @param req The request. + */ + const rewriteCMLocationHeader = (res, req) => { + const location = res.getHeader("location"); + if (!location) { return; } @@ -81,6 +115,19 @@ module.exports = (env) => { locationUrl.protocol = "http"; locationUrl.host = requestHost; + const redirectParam = locationUrl.searchParams.get("redirect"); + + if (redirectParam) { + const redirectUrl = new URL(redirectParam); + + if (redirectUrl.host == backendUrl.host) { + redirectUrl.protocol = "http"; + redirectUrl.host = requestHost; + + locationUrl.searchParams.set("redirect", redirectUrl.href); + } + } + res.setHeader("location", locationUrl.href); };