我有一个 Node.js Express 3.0 应用程序,它在本地监听端口 3000,在线监听端口 80,没问题。不过,我现在需要做的是引入 SSL 证书。
我在网上查看了很多资源,但它们都已过时,或者只能在端口 443 上工作,或者什么都没有。然而,我需要做的是同时监听 443 和 80,并将任何发往 80 的请求重定向回 443。
他们有最新的例子吗?
最佳答案
我会用 2 个不同的进程来做到这一点:一个不安全的代理服务器和一个安全的服务器。
不安全的代理监听端口 80 并通过 302 重定向到安全服务器响应所有请求
不安全的代理
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)
})
请注意,您可以在单个进程中运行这两个服务器,但将关注点分离到不同的进程中更易于维护。
关于node.js - express 3.0 HTTPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15839253/