Last active
April 27, 2024 08:52
Manage redirection with node js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// exemple de base, à adapter à votre besoin | |
app.use((req, res, next) => { | |
const originalUrl = req.originalUrl; | |
if (originalUrl === '/' || originalUrl.slice(-1) !== '/') { | |
return next() | |
} | |
const baseUrlWithoutTrailingSlashes = originalUrl.replace(/\/+$/, ''); | |
const hasTrailingSlashes = originalUrl !== baseUrlWithoutTrailingSlashes; | |
if (hasTrailingSlashes) { | |
const queryIndex = originalUrl.indexOf('?'); | |
let newUrl = baseUrlWithoutTrailingSlashes; | |
if (queryIndex > -1) { | |
newUrl += originalUrl.substring(queryIndex); | |
} | |
return res.redirect(301, newUrl); | |
} | |
next(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment