Redirect all trailing slashes globally in express

后端 未结 7 1685
醉话见心
醉话见心 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:12

    The answers above will work in a lot of cases but GET vars can encounter issues and if you were to put that inside another express middleware its reliance on req.path will cause a problem and its reliance on req.url can also have unwanted side effects. If you're looking for a tighter solution this will do the trick:

    // Redirect non trailing slash to trailing slash
    app.use(function(req, res, next){
        // Find the query string
        var qsi = req.originalUrl.indexOf('?');
        // Get the path
        var path = req.originalUrl;
        if(qsi > -1) path = path.substr(0, qsi);
        // Continue if the path is good or it's a static resource
        if(path.substr(-1) === '/' || ~path.indexOf('.')) return next();
        // Save just the query string
        var qs = '';
        if(qsi > -1) qs = req.originalUrl.substr(qsi);
        // Save redirect path
        var redirect = path + '/' + qs;
        // Redirect client
        res.redirect(301, redirect);
    
        console.log('301 redirected ' + req.originalUrl + ' to ' + redirect);
    });
    

    It's always happy with GET variables and won't break if you were to put it inside middleware.

提交回复
热议问题