Node.js Redirect URL

Node.js Redirect URL : In this tutorial, we shall learn to redirect a url.

A redirect could be applied in situations like :

  • Some of the resources are moved permanently to a new location and you want to redirect your users to the new location of moved resources.
  • Some of the pages in your web application are removed, and when a request comes for that page, you would like your users be redirected to home page or some custom page.

There are three main types of HTTP redirects. Please refer wiki page for redirects[https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection].

But remember that the HTTP redirect code (say 301, 302, 307, etc.,) affect the page ranking for the original or redirected url, and each of the redirect codes affect differently. For example, if you have moved the resource permanently, using 301 HTTP code in the response passes the juice to the redirected URL, while 302 or 307 does not.

For the following examples, consider that there are two pages : page-a.html and page-b.html, that your web application serves. And we have a 404_not_found.html to be displayed when a requested resource is not present.

Example 1 – Node.js Redirect URL

In this example, we shall demonstrate the scenario where the requested URL has to be redirected. When we get a request for page-c.html, we shall send a redirect response (to look for page-b.html) to the web-client.

node-js-http-redirect.js

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

// create a http server
http.createServer(function (req, res) {
	
	if (req.url == '/page-c.html') {
		// redirect to page-b.html with 301 (Moved Permanently) HTTP code in the response
		res.writeHead(301, { "Location": "http://" + req.headers['host'] + '/page-b.html' });
		return res.end();
	} else {
		// for other URLs, try responding with the page
		console.log(req.url)
		// read requested file
		fs.readFile(req.url.substring(1),
			function(err, data) {		
				if (err) throw err;
				res.writeHead(200);
				res.write(data.toString('utf8'));
				return res.end();
		});
	} 
}).listen(8085);
$ node node-js-http-redirect.js

Open a browser, display Developer Tools, and hit the URL "http://localhost:8085/page-c.html".

In the Network section of Developer Tools, you would find that the request has been redirected to a new page.

ADVERTISEMENT
Node.js Redirect URL Example

For the first request, there was a 301 response code which we have sent from our Node.js application.

Example 2 – Node.js Redirect URL – File not found error

In this example, we shall demonstrate the scenario that the requested file is not found. But you don’t want to show your web client the uninteresting 404 error page. Instead, you would like to show some other page, like page-a.html.

node-js-http-redirect-file-not-found.js

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

// create a http server
http.createServer(function (req, res) {
	var filePath = req.url.substring(1);
	fs.readFile(filePath,
		function(err, data) {		
			// if there is an error reading the file, redirect it to page-b.html
			if (err){
				// redirect to page-b.html with 302 HTTP code in response
				res.writeHead(302, { "Location": "http://" + req.headers['host'] + '/page-b.html' });
				return res.end();
			}
			res.writeHead(200);
			res.write(data.toString('utf8'));
			return res.end();
	});
}).listen(8085);

Open a terminal or command prompt and run this script using node command as shown in the following.

Output

$ node node-js-http-redirect-file-not-found.js

Open a browser, display Developer Tools, and hit the url “http://localhost:8085/page-n.html”.

In the Network section of Developer Tools, you would find that the request has been redirected to a new page, with 302(Temporarily moved) HTTP Code in the response.

Node.js Redirect Page Not Found

Conclusion

In this Node.js Tutorial, we have learnt how to redirect a URL in Node.js Server.