Nodejs - Redirect url

node.jsRedirect

node.js Problem Overview


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.

node.js Solutions


Solution 1 - node.js

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

Solution 2 - node.js

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

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

Solution 3 - node.js

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

Solution 4 - node.js

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

Solution 5 - node.js

Try this:

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

Solution 6 - node.js

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

Solution 7 - node.js

You have to use the following code:

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

Solution 8 - node.js

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDzung NguyenView Question on Stackoverflow
Solution 1 - node.jsChetan SView Answer on Stackoverflow
Solution 2 - node.jsDaniël W. CromptonView Answer on Stackoverflow
Solution 3 - node.jsChandra SekarView Answer on Stackoverflow
Solution 4 - node.jsLeviteView Answer on Stackoverflow
Solution 5 - node.jsMikeView Answer on Stackoverflow
Solution 6 - node.jsAlon and IdanView Answer on Stackoverflow
Solution 7 - node.jsArash KeivanView Answer on Stackoverflow
Solution 8 - node.jsKrishnamoorthy AcharyaView Answer on Stackoverflow