Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

javascript - express 4.x redirect http to https

I have the following code :

var https        = require('https');
var http         = require('http');
var express      = require('express');
var app          = express();
var router       = express.Router();

app.use('/', router);

//have 'server' listen for https
var server = https.createServer(config.sslCredential, app);
server.listen(config.serverPort);

//listen server on http, and always redirect to https
var httpServer = http.createServer(function(req,res){
    res.redirect(config.serverDomain+req.url);
});
httpServer.listen(config.httpServerPort);

but somehow I can't get the https request to be redirected into https request, how should I do this correctly on node.js with express 4.x ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Quoting a middleware solution from my own answer (which btw was on express 3.0)

app.all('*', ensureSecure); // at top of routing calls

http.createServer(app).listen(80)
https.createServer(sslOptions, app).listen(443)

function ensureSecure(req, res, next){
  if(req.secure){
    // OK, continue
    return next();
  };
  // handle port numbers if you need non defaults
  // res.redirect('https://' + req.host + req.url); // express 3.x
  res.redirect('https://' + req.hostname + req.url); // express 4.x
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...