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

Problem

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

app.get('/', function(req,res){
    locals.date = 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 myapp.com/lessons and myapp.com/lessons/ 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

Thanks

Problem courtesy of: Michael

Solution

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));
   else
       next();
});
Solution courtesy of: Tolga Akyüz

Discussion

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

×