Skip to content

Commit

Permalink
Fix webpack dev-server handling of relative links. (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
tdilauro authored Nov 7, 2023
1 parent a15eff4 commit a24441d
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions webpack.dev-server.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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);
};

Expand Down

0 comments on commit a24441d

Please sign in to comment.