Force SSL with expressjs 3
I don't really understand the point in starting two servers when only one can do the job perfectly. For example, by adding a simple middleware in your server file:
app.use(function(req, res, next) { if(!req.secure) { return res.redirect(['https://', req.get('Host'), req.url].join('')); } next();});
This will redirect any non-secure request to the corresponding HTTPS page. For example, http://example.com/
to https://example.com/
and http://example.com/foo?bar=woo
to https://example.com/foo?bar=woo
. This is definitely the behavior I would expect. Maybe you should filter this by host, so it redirects only on domains for which you own and installed a proper certificate.
If your app is running behind another server like Nginx, you may want to add the configuration parameter app.set('trust proxy', true)
. Or, even better, make Nginx do the redirect itself, which will be more efficient than any Node.js app.
Edit: According to my benchmarks, join
is a little faster than +
for concatenating strings. Nothing dramatic, but every win is a win...
I had a similar problem and the redirect solution is not suitable for me because essentially I want to get rid of the browser's insecure warning,
So instead of redirect every message, I did:
app1 = new express()app1.get('/', function(req, res) {res.sendFile(path.join(__dirname + '/redirect.html'));
}); app1.listen(80, function(){'redirect server running on 80 port'})
and in the redirect.html is just a redirecting html file:
<meta http-equiv="refresh" content="0; URL='https://my-site.com'" />
Of course, this won't work for complicated cases when you want to redirect all routings, but for me, I only want to redirect my homepage to my https homepage and get rid of the browser's insecure warning. Hope this help somebody!
You should create a second server listening on 80 and redirect with a 301 header to your https server:
var express = require('express');var app = express();app.get('/', function(req, res, next){ res.redirect('https://' + app.address().address)});app.listen(80);