Redirect all trailing slashes globally in express

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

    The answer by Tolga Akyüz is inspiring but doesn't work if there is any characters after the slash. For example http://example.com/api/?q=a is redirected to http://example.com/api instead of http://example.com/api?q=a.

    Here is an improved version of the proposed middleware that fix the problem by adding the original query to the end of the redirect destination url:

    app.use(function(req, res, next) {
        if (req.path.substr(-1) == '/' && req.path.length > 1) {
            var query = req.url.slice(req.path.length);
            res.redirect(301, req.path.slice(0, -1) + query);
        } else {
            next();
        }
    });
    

    Note: As noted by jamesk and stated in RFC 1738, the trailing slash can only be omitted when there is nothing after the domain. Therefore, http://example.com?q=a is an invalid url where http://example.com/?q=a is a valid one. In such case, no redirection should be done. Fortunately, the expression req.path.length > 1 takes care of that. For example, given the url http://example.com/?q=a, the path req.path equals to / and thus the redirection is avoided.

提交回复
热议问题