Node.js Redirect URL

Node.js Redirect URL : In this Node.js 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.

Node.js Redirect URL Example

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.

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.

Node.js Redirect URL Example

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

Node.js Redirect URL Example – 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.

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