w3docs logo
  1. Snippets
  2. NodeJs
  3. How to Redirect a Web Page with Node.js

How to Redirect a Web Page with Node.js

Let us show you how to redirect a web page with Node.js.

First step is to include the http module and create a new server, then use the createServer method (.writeHead and .end ):

Use the createServer method:

Example

var http = require("http");

http
  .createServer(function (req, res) {
    res.writeHead(301, { Location: "http://w3docs.com" });
    res.end();
  })
  .listen(8888);

Use url module to redirect all the posts in the /blog section:

Example

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

http
  .createServer(function (req, res) {
    var pathname = url.parse(req.url).pathname;
    res.writeHead(301, { Location: "http://w3docs.com/" + pathname });
    res.end();
  })
  .listen(8888);

.writeHead() function lets you attach the pathname from the request to the end of URL string. So you can redirect to the same path on your new site.

To request for a page-c.html send a redirect response (to look for page-b.html) to the web-client:

Example

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

Learn more about how to redirect pages with HTML, JavaScript, PHP, and Apache

Do you find this helpful?