3

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?

apscience
  • 7,033
  • 11
  • 55
  • 89

2 Answers2

7

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);
1

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.

Vivek Bajpai
  • 1,617
  • 1
  • 19
  • 35
  • Could u pls explain hw do you want to handle these without www request ? and Why dont you use nginx before your application or any proxy server which will filter the request before passing to express – Vivek Bajpai Jul 28 '13 at 20:11
  • I do not use express. It is okay, I did it on the client instead. – apscience Jul 29 '13 at 06:35
  • Ohh okk so what are you using for appserver is it in nodejs ? – Vivek Bajpai Jul 29 '13 at 06:47
  • Yes but the problem has already been solved, not this answer through. I'll make yours as the solution – apscience Jul 29 '13 at 06:49
  • @gladoscc actually i hv went through the same problem as yours , i solved it by using nginx as proxy sever and redirects these two request internally two different app server. Thats why i ask u all the detail but any ways its great that you solved it :) – Vivek Bajpai Jul 29 '13 at 06:55
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/34349/discussion-between-vivek-bajpai-and-gladoscc) – Vivek Bajpai Jul 29 '13 at 07:01