Joseph Jude

Consult . Code . Coach

Redirecting a URL using nodejs


code . nodejs

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

Some of the articles from tech.jjude.com 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 tech.jjude.com 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 http://tech.jjude.com/dlite to urls like http://jjude.com/dlite. 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 = 'jjude.com';

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, http://tech.jjude.com/dlite, it will be routed to https://jjude.com/dlite.


Like the post? Retweet it. Got comments? Reply.

Redirecting a URL using nodejs by @jjude https://t.co/L6B0vofCsx

— Joseph Jude (@jjude) October 27, 2016
Share this on: Twitter / /

Comments

comments powered by Disqus