Skip to content

Instantly share code, notes, and snippets.

@veritstudio
Last active December 1, 2018 14:03
Show Gist options
  • Save veritstudio/9faa208d93a762d8af390b34cfce2d21 to your computer and use it in GitHub Desktop.
Save veritstudio/9faa208d93a762d8af390b34cfce2d21 to your computer and use it in GitHub Desktop.
Middleware to redirect trailing slash with query parameters
const url = require('url')
module.exports = (config) => {
return (req, res, next) => {
let current = req.protocol + '//' + req.get('host') + req.originalUrl,
withSlash = addSlash(current)
if (current == withSlash) {
next()
} else {
res.redirect(withSlash)
}
}
function addSlash(original) {
let parsedUrl = url.parse(original)
if (parsedUrl.pathname.slice(-1) === '/') {
return original
} else {
return original.replace(parsedUrl.pathname, parsedUrl.pathname + '/')
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment