From 3613aa92d204511ae8faff937e6bfa33832472ce Mon Sep 17 00:00:00 2001 From: Dorian Niemiec Date: Sat, 24 Aug 2024 20:40:28 +0200 Subject: [PATCH] Add trailing slash redirection middleware. --- src/index.js | 3 +- src/middleware/redirectTrailingSlashes.js | 42 +++++++++++++++++++++++ src/middleware/rewriteURL.js | 2 ++ 3 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 src/middleware/redirectTrailingSlashes.js diff --git a/src/index.js b/src/index.js index 0df44bc..1b51c6f 100644 --- a/src/index.js +++ b/src/index.js @@ -185,7 +185,8 @@ let middleware = [ require("./middleware/rewriteURL.js"), require("./middleware/responseHeaders.js"), require("./middleware/checkForbiddenPaths.js"), - require("./middleware/nonStandardCodesAndHttpAuthentication.js") + require("./middleware/nonStandardCodesAndHttpAuthentication.js"), + require("./middleware/redirectTrailingSlashes.js") ]; function addMiddleware(mw) { diff --git a/src/middleware/redirectTrailingSlashes.js b/src/middleware/redirectTrailingSlashes.js new file mode 100644 index 0000000..af29b7a --- /dev/null +++ b/src/middleware/redirectTrailingSlashes.js @@ -0,0 +1,42 @@ +const fs = require("fs"); +const url = require("url"); + +module.exports = (req, res, logFacilities, config, next) => { + // Trailing slash redirection + if ( + !req.isProxy && + !config.disableTrailingSlashRedirects && + req.parsedURL.pathname[req.parsedURL.pathname.length - 1] != "/" && + req.originalParsedURL.pathname[ + req.originalParsedURL.pathname.length - 1 + ] != "/" + ) { + fs.stat( + "." + decodeURIComponent(req.parsedURL.pathname), + function (err, stats) { + if (err || !stats.isDirectory()) { + try { + next(); + } catch (err) { + res.error(500, err); + } + } else { + var destinationURL = new url.Url(); + destinationURL.path = null; + destinationURL.href = null; + destinationURL.pathname = req.originalParsedURL.pathname + "/"; + destinationURL.hostname = null; + destinationURL.host = null; + destinationURL.port = null; + destinationURL.protocol = null; + destinationURL.slashes = null; + destinationURL = url.format(destinationURL); + res.redirect(destinationURL); + } + }, + ); + } else { + next(); + } + +}; diff --git a/src/middleware/rewriteURL.js b/src/middleware/rewriteURL.js index edf236c..4858bdf 100644 --- a/src/middleware/rewriteURL.js +++ b/src/middleware/rewriteURL.js @@ -12,6 +12,8 @@ module.exports = (req, res, logFacilities, config, next) => { res.error(400); } + req.originalParsedURL = req.parsedURL; + // Handle URL rewriting const rewriteURL = (address, map, callback, _fileState, _mapBegIndex) => { let rewrittenURL = address;