Last Updated: February 25, 2016
·
1.216K
· 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
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside