Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Redirect all trailing slashes globally in express

Redirect all trailing slashes globally in express


I am using Node.js and Express and I have the following routing :

app.get('/', function(req,res){ = new Date().toLocaleDateString();

    res.render('home.ejs', locals);

function lessonsRouter (req, res, next)
    var lesson = req.params.lesson;
    res.render('lessons/' + lesson + '.ejs', locals_lessons);

app.get('/lessons/:lesson*', lessonsRouter);

function viewsRouter (req, res, next)
    var controllerName = req.params.controllerName;
    res.render(controllerName + '.ejs', locals_lessons);
app.get('/:controllerName', viewsRouter);

I have a Disqus widget on my lessons pages and I have noticed a strange behavior that when going to and I get two different pages (on of them had a comment I previously added in Disqus and the other one doesn't have a comment).

Is there a way to "canonize" all of my urls to be without Trailing Slashes ? I have tried to add the strict routing flag to express but the results were the same


Problem courtesy of: Michael


Try adding a middleware for that;

app.use(function(req, res, next) {
   if(req.url.substr(-1) == '/' && req.url.length > 1)
       res.redirect(301, req.url.slice(0, -1));
Solution courtesy of: Tolga Akyüz


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Redirect all trailing slashes globally in express


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription