Bit Hacker Logo
Bit Hacker Logo
Move your Domain using a 301 Redirect with Express

Move your Domain using a 301 Redirect with Express

BitHacker recently underwent a domain change from the old bytemaster.io domain. During the process, we needed to create redirects of all our content to the new site. It was important that we preserved all slugs and used a 301 Redirect, a permanent redirect to keep as much SEO "juice" as possible. Below is how we did it!

A new express App

We run BitHacker on Nuxt.js and love it, however to avoid unnecessary frameworks, it was more fitting to create a simple Node.js Express Redirect script. Redirecting is not that complicated, after all. To start, we setup a stand-alone express app:

const express = require('express');
const app = express();
const port = 3000;

app.listen(port, () => console.log(`Redirector ${port}!`));

Next we will add a request listener for any (*) request:

// includes

app.all('*', function(req, res) {
});

// app.listen

Inside this function we return a response telling the browser to redirect all requests to the new location. We will also add the request path to the new destination to send the user to the same spot. Using a 301 as the first parameter sets the type of redirect. The 301 is a Permanent redirect telling search engines to remember it forever. For temporary redirects, 302 can be used.

app.all('*', function(req, res) {
  return res.redirect(301,`https://bithacker.dev${req.path}`);
});

Testing

To give it a local test, save it has redirector.js and run:

node redirector.js

Now, fire up your browser and head over to http://localhost:3000/move-domain-301-redirect-with-express and you should reach this very article!

That's it!

Deploying

Running this on your server can vary, and is outside the scope of this article. If you are running an existing Node.js app, you should be able to use the same port as your existing application and be all set.

If it is a single application on one server, using port 80 behind your web server would do the trick.

Final Code

const express = require('express');
const app = express();
const port = 3000;

app.all('*', function(req, res) {
    return res.redirect(301,`https://bithacker.dev${req.path}`);
});

app.listen(port, () => console.log(`Redirector ${port}!`));