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

1.Use the createServer method:


var http = require("http");

http.createServer(function(req, res) {
  res.writeHead(301,{Location: ''});

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


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

http.createServer(function(req, res) {
  var pathname = url.parse(req.url).pathname;
  res.writeHead(301,{Location: '' + pathname});

.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.

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


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
        // read requested file
            function(err, data) {        
                if (err) throw err;
                return res.end();

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

Do you find this helpful?

Related articles