Last Updated: February 25, 2016
·
619
· leecrossley

Ditch the www in expressjs

It's 2014, people know what the world wide web is. It's time to redirect that www subdomain:

var redirect = function (req, res, next) {
    var baseUrl = req.protocol + "://" + req.host,
        wwwUrl = req.protocol + "://www.";
    if (baseUrl.substring(0, wwwUrl.length) === wwwUrl) {
        res.redirect(301, baseUrl.replace("://www.", "://") + req.url);
    } else {
        next();
    }
};

app.all("*", redirect);

Full blog post at ilee.co.uk/ditch-the-www-subdomain

Have a fresh tip? Share with Coderwall community!

Post
Post a tip