node.js expressjs pattern match not equal

I'm using expressjs with node and running both https and http.

I want to require that all routes for /secure/* use https. This is done:

app.all("/secure/*", function(req, res, next) {
    if (!req.connection.encrypted) {
        res.redirect("https://" + req.headers["host"].replace(new RegExp(config.http_port, "g"), config.https_port) + req.url); 
    } else {
        return next();
    };
});

However, I also want to require that all routes that are not using /secure/* and try to access https, are redirected using the same method to http.

I tried doing this:

app.all("*", function(req, res, next) {
    console.log(req);
    if (req.connection.encrypted) {
        res.redirect("http://" + req.headers["host"].replace(new RegExp(config.https_port, "g"), config.http_port) + req.url); 
    } else {
        return next();
    };
});

But I end up in a redirect loop when accessing the https pages. Is there a way to specify all routes, except those with /secure/* ?

Thank you!

A simple solution to your problem is:

app.all("*", function(req, res, next) {
    if (req.connection.encrypted && !/^\/secure/.test(req.url)) {
        res.redirect("http://" + req.headers["host"].replace(new RegExp(config.https_port, "g"), config.http_port) + req.url); 
    } else {
        return next();
    };
});

Only do the redirect if the URL doesn't start with /secure.

However, I'd propose that instead of the redundant 'secure' label in the URLs, just mark certain paths as requireHTTP or requireHTTPS. You know you can pass multiple methods into app.get and other such router methods, right? Assuming you define requireHTTP and requireHTTPS (which would be identical to your original functions), you'd just do:

app.get("/path/to/keep/encrypted", requireHTTPS, function(req, res) {
    // Rest of controller
});

app.get("/path/to/keep/public", requireHTTP, function(req, res) {
    // Rest of controller
});

app.get("/path/you/dont/care/about/encryption/status", function(req, res) {
    // Rest of controller
});

That should do it.