Tzu ng
Tzu ng

Reputation: 9244

Nodejs - Redirect url

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.

Upvotes: 153

Views: 343538

Answers (9)

Gouranga Satapathy
Gouranga Satapathy

Reputation: 432

use

res.redirect('/path/404.html');

or you can redirect to any defined URI as

res.redirect('/');

Upvotes: -2

Daniël W. Crompton
Daniël W. Crompton

Reputation: 3518

If you are using ExpressJS, it's possible to use:

res.redirect('your/404/path.html');

Upvotes: 89

Krishnamoorthy Acharya
Krishnamoorthy Acharya

Reputation: 4254

Use the following code this works fine in Native Nodejs

http.createServer(function (req, res) {
var q = url.parse(req.url, true);
if (q.pathname === '/') {
  //Home page code
} else if (q.pathname === '/redirect-to-google') {
  res.writeHead(301, { "Location": "http://google.com/" });
  return res.end();
} else if (q.pathname === '/redirect-to-interal-page') {
  res.writeHead(301, { "Location": "/path/within/site" });
  return res.end();
} else {
    //404 page code
}
res.end();
}).listen(8080);

Upvotes: 2

Arash Keivan
Arash Keivan

Reputation: 39

You have to use the following code:

response.writeHead(302 , {
           'Location' : '/view/index.html' // This is your url which you want
        });
response.end();

Upvotes: 3

Alon and Idan
Alon and Idan

Reputation: 87

I used a switch statement, with the default as a 404:

var fs = require("fs");
var http = require("http");

function send404Response (response){
    response.writeHead(404, {"Content-Type": "text/html"});
    fs.createReadStream("./path/to/404.html").pipe(response);
}

function onRequest (request, response){
    switch (request.url){
        case "/page1":
            //statements
            break;
        case "/page2":
            //statements
            break;
        default:
        //if no 'match' is found
            send404Response(response);
            break;
    }
}

http.createServer(onRequest).listen(8080);

Upvotes: 6

Mike
Mike

Reputation: 67

Try this:

this.statusCode = 302;
this.setHeader('Location', '/url/to/redirect');
this.end();

Upvotes: 5

Levite
Levite

Reputation: 17637

404 with Content/Body

res.writeHead(404, {'Content-Type': 'text/plain'});                    // <- redirect
res.write("Looked everywhere, but couldn't find that page at all!\n"); // <- content!
res.end();                                                             // that's all!

Redirect to Https

res.writeHead(302, {'Location': 'https://example.com' + req.url});
res.end();

Just consider where you use this (e.g. only for http request), so you don't get endless redirects ;-)

Upvotes: 16

Chandra Sekar
Chandra Sekar

Reputation: 10853

To indicate a missing file/resource and serve a 404 page, you need not redirect. In the same request you must generate the response with the status code set to 404 and the content of your 404 HTML page as response body. Here is the sample code to demonstrate this in Node.js.

var http = require('http'),
    fs = require('fs'),
    util = require('util'),
    url = require('url');

var server = http.createServer(function(req, res) {
    if(url.parse(req.url).pathname == '/') {
        res.writeHead(200, {'content-type': 'text/html'});
        var rs = fs.createReadStream('index.html');
        util.pump(rs, res);
    } else {
        res.writeHead(404, {'content-type': 'text/html'});
        var rs = fs.createReadStream('404.html');
        util.pump(rs, res);
    }
});

server.listen(8080);

Upvotes: 18

Chetan S
Chetan S

Reputation: 23813

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

Upvotes: 246

Related Questions