Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: 301 redirect non-www without express

Tags:

node.js

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?

like image 479
apscience Avatar asked Nov 19 '25 13:11

apscience


2 Answers

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);
like image 83
Javier Garmón Avatar answered Nov 21 '25 04:11

Javier Garmón


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.

like image 30
Vivek Bajpai Avatar answered Nov 21 '25 02:11

Vivek Bajpai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!