简体   繁体   中英

Node.js: 301 redirect non-www without express

For an existing project, I'd like to just do a simple change of redirecting www.mysite.com to mysite.com (because cookie issues, cookies on www. isn't accessible to non-www version). I do not want to include express.

How can I do this simple change?

I think this is what you're looking for:

var http = require("http");

    http.createServer(function (req, res) {
    res.writeHead(301, {"Location": "http://example.com"});
    res.end();

}).listen(80);

UPDATE : Its not the suitable answer for question.

Why dont you try to filter non www request with this

app.get ('/*', function (req, res, next){
if (req.headers.host.match(/^www\./))

  {
    res.writeHead (301, {'Location': 'http://example.com'});

    }
else { 

   return next();
    }

} );

You should consider it only for express and if you want to like redirect before express then you should try Nginx before express or any reverse proxy server so that request can be filter before sending to express.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM