Joseph Jude

Redirecting a URL using nodejs

2016.10.27 / code / nodejs /

Merged sites? Don't want to lose traffic to old site? Redirect with a simple app.

I had two blogs:, which was the main site and, where I wrote tech articles. I wanted to simplify my blogging, so I merged both sites. It was a simple merge — all articles in were merged into under the same slug.

Some of the articles from were linked from other sites like Stackoverflow and I didn’t want to lose such traffic. So I decided to write a web-app that will route any traffic coming to to the new url.

I could’ve written a redirect app in any language. Since I started trying nodejs again, I thought I will write this app in nodejs.

Create a new directory and start a new node project by issuing, npm init -y. This will create a package.json file. This is a simple application which uses only the standard library. So there is no big deal about this package.json.

My requirement was simple and hence the logic is also simple: redirect urls like to urls like The slugs were the same, only the base url changes. So I had to capture the slug, prepend with the new url and redirect. Because it is a permanent redirect, set the status code to 301.

In nodejs, pathname property of the url object gets everything after the url, including any query string.

With that bit of logic, here is the code to redirect a url:

const http = require('http'),
  url = require('url'),
  server = http.createServer().listen(process.env.PORT || 3000);

const baseUrl = '';

server.on('request', (req, res) => {
  var newUrl = baseUrl + url.parse(req.url).pathname;

  res.statusCode = 301;
  res.setHeader('Content-Type', 'text/plain');
  res.setHeader('Location', newUrl);
  res.end('Redirecting to ' + newUrl);

I use PM2 to manage the nodejs apps. Here is the pm2.json file to manage this app.

   * start with pm2 start pm2.json --env production
  "apps" : [
      "name"      : "urlforward",
      "script"    : "./index.js",
      "exec_mode" : "cluster",
      "instances": 2,
      "env": {
        "NODE_ENV": "development"
      "env_production" : {
        "NODE_ENV": "production",
        "PORT": 11111

You can issue, pm2 ls, to see if this app is running.

Now if you go to,, it will be routed to

Thanks for reading. Would you please let others know by sharing in Twitter?