Redirect all trailing slashes globally in express

后端 未结 7 1691
醉话见心
醉话见心 2020-11-28 23:40

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

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

    r         


        
7条回答
  •  一个人的身影
    2020-11-29 00:34

    One liner:

    router.get('\\S+\/$', function (req, res) {
      return res.redirect(301, req.path.slice(0, -1) + req.url.slice(req.path.length));
    });
    

    This will only catch the url's that need to be redirected, and ignore the others.

    Example results:

    /         ==> /
    /a        ==> /a
    /a/       ==> /a
    /a/b      ==> /a/b
    /a/b/     ==> /a/b
    /a/b/?c=d ==> /a/b?c=d
    

提交回复
热议问题