I am Hack Sparrow
Captain of the Internets.

How to forward non-www to www domain name and vice-versa in Node.js (Express)?

Forwarding domain names according to the requirements of 'www' is trivial in Apache using .htaccess. It's not hard either in Node.js, if you are using Express.

Put the route definition of your requirement on top of all other routes in Express.

Forward www to non-www domain name


This will detect the presence of 'www' and redirect the request to the domain name without 'www'. The status code of 301 means that it is a permanent redirect. If you omit the status code it does a 302 (temporary redirect). For SEO purposes it is best to use a 301 redirect.

app.get('/*', function(req, res, next) {
if (req.headers.host.match(/^www/) !== null ) res.redirect('http://' + req.headers.host.replace(/^www\./, '') + req.url, 301);
else next();
});

Forward non-www to www domain name


This route detects the absence of 'www' and redirects the request to the domain name with 'www'.

// TODO: non-www to www redirect
app.get('/*', function(req, res, next) {
if (req.headers.host.match(/^www/) == null ) res.redirect('http://www.' + req.headers.host + req.url, 301);
else next();
});

As simple as that!

One Response to “How to forward non-www to www domain name and vice-versa in Node.js (Express)?”

  1. Storm says:

    Hey, very thanks 🙂

Make a Comment