forked from svrjs/svrjs
Add trailing slash redirection middleware.
This commit is contained in:
parent
c1900ee128
commit
3613aa92d2
3 changed files with 46 additions and 1 deletions
|
@ -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) {
|
||||
|
|
42
src/middleware/redirectTrailingSlashes.js
Normal file
42
src/middleware/redirectTrailingSlashes.js
Normal file
|
@ -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();
|
||||
}
|
||||
|
||||
};
|
|
@ -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;
|
||||
|
|
Reference in a new issue