Nodejs - Redirect url

Dzung Nguyen picture Dzung Nguyen · Oct 31, 2010 · Viewed 248.1k times · Source

How do I get a node.js server to redirect users to a 404.html page when they enter an invalid url?

I did some searching, and it looks like most results are for Express, but I want to write my server in pure node.js.

Answer

Chetan S picture Chetan S · Oct 31, 2010

The logic of determining a "wrong" url is specific to your application. It could be a simple file not found error or something else if you are doing a RESTful app. Once you've figured that out, sending a redirect is as simple as:

response.writeHead(302, {
  'Location': 'your/404/path.html'
  //add other headers here...
});
response.end();