Express 3.0 HTTPS

我有一个Node.js Express 3.0应用程序,它在本地监听端口3000,在线监听80端口,这很好。 现在我需要做的是引入一个SSL证书。

我已经在网上查看了很多来源,但是它们都是过时的,或者只在端口443上工作,或者什么也不是。 然而,我需要做的是听取443和80,然后把任何要求重新定向到80到443。

他们是否有任何最新的例子?

我会用2个不同的进程来做到这一点:一个不安全的代理服务器和一个安全的服务器。

不安全的代理侦听端口80,并以302redirect到安全服务器来响应所有请求

不安全的代理

var http = require('http') var port = 80 var server = http.createServer(function (req, res) { // change this to your secure sever url var redirectURL = 'https://www.google.com' res.writeHead(302, { Location: redirectURL }); res.end(); }).listen(port, function () { console.log('insecure proxy listening on port: ' + port) }) 

安全服务器

 var https = require('https') var express = require('express') var fs = require('fs') var keyFilePath = '/path/to/key.pem' var certFilePath = '/path/to/cert.pem' var app = express() // put your express app config here // app.use(...) etc. var port = 443 // standard https port var options = { key: fs.readFileSync(keyFilePath, 'utf8'), cert: fs.readFileSync(certFilePath, 'utf8') } var server = https.createServer(options, app) server.listen(port, function () { console.log('secure server listening on port: ' + port) }) 

请注意,您可以在单个进程中运行这两个服务器,但将关注点分离为不同的进程更易于维护。