Loading

Redirect non-www to www domain name and vice-versa

Redirect non-www to www domain name and vice-versa

Forwarding all requests of your website either your domain prefixed by “www” or by your domain directly. It is more important for SEO. In Apache, this is achieved via your .htaccess file. It's not hard either in Node.js if you are using Express. It is easy to add middleware to achieve this.

# Redirect non-www to www domain name

app.use((req, res, next) => {
    const host = req.header('host');
    if (host.match(/^www\..*/i)) {
        next();
    } else {
        res.redirect(301, `${req.protocol}://www.${host}${req.url}`);
    }
});

# Redirect www to non-www domain name

app.use((req, res, next) => {
    const host = req.header('host');
    if (host.match(/^www\..*/i)) {
         res.redirect(301, `${req.protocol}://${host}${req.url}`);
    } else {
         next();
    }
});

For every request it checks if the host starts with www. If it does, it takes the original URL and redirects it to the non-www version with a 301 redirect.

Note: In order to use req.protocol reliably behind a proxy performing SSL termination (such as Elastic Load Balancer), you need to make sure that the trust proxy setting is enabled.

app.set('trust proxy', true);

Alternatively, you can use a ready-made module for Express that does exactly what you want, e.g. node-force-domain. See https://github.com/goloroden/node-force-domain for details.

Related Articles