Node.js www - non www redirection

前端 未结 6 1436
花落未央
花落未央 2020-12-13 00:14

Is there a chance to somehow redirect www to non-www URLs in node.js? Since there is no htaccess in node web server I am curious how to do that.

6条回答
  •  忘掉有多难
    2020-12-13 00:58

    This is a basic exemple of how you could mimic the behavior of the redirect directive of apache in nodejs.

    The function redirect takes either a RegExp or a string.

    var http, redirect;
    http = require("http");
    redirect = function(host, res, pattern, redirect){
        if (host == pattern || (pattern instanceof RegExp && host.match(pattern))) {
            console.log("Redirected " + host);
            res.writeHead(302, {
            'location': redirect
        });
        res.end();
    }};
    
    http.createServer(function(req, res){
        redirect(req.headers.host, res, /^www/, 'http://plouf.url');
        redirect(req.headers.host, res, 'www.plouf.url', 'http://plouf.url');
        res.writeHead(200, {
            'Content-Type': 'text/plain'
        });
        res.end('Hello World\n');
    }).listen(8000, '127.0.0.1');
    

提交回复
热议问题