我正在使用
部署 Node js 服务器npm run start
它工作正常。现在我想添加 ssl 私钥,因此我添加了下面的 https_server.js 文件:
var https = require('https');
var fs = require('fs');
var https_options = {
key: fs.readFileSync("/home/user/org.key"),
cert: fs.readFileSync('/home/user/cert.pem')
};
https.createServer(https_options , function (req, res) {
res.writeHead(200);
res.end("Welcome to Node.js HTTPS Servern");
}).listen(3000,'0.0.0.0')
然后我运行
node https_server.js
因此,当我运行此命令时,它显示“欢迎使用 Node.js HTTPS Servern”,而不是 Web 应用程序的主页。 我应该更改这部分吗
res.end("Welcome to Node.js HTTPS Servern");
感谢任何帮助。
编辑
我也尝试过
var fs = require('fs');
var net = require('net');
var http = require('http');
var https = require('https');
var baseAddress = 3000;
var redirectAddress = 3001;
var httpsAddress = 3002;
var httpsOptions = {
key: fs.readFileSync('/home/user/org.key'),
cert: fs.readFileSync('/home/user/cert.pem')
};
net.createServer(tcpConnection).listen(baseAddress);
http.createServer(httpConnection).listen(redirectAddress);
https.createServer(httpsOptions, httpsConnection).listen(httpsAddress);
function tcpConnection(conn) {
conn.once('data', function (buf) {
// A TLS handshake record starts with byte 22.
var address = (buf[0] === 22) ? httpsAddress : redirectAddress;
var proxy = net.createConnection(address, function () {
proxy.write(buf);
conn.pipe(proxy).pipe(conn);
});
});
}
function httpConnection(req, res) {
var host = req.headers['host'];
res.writeHead(301, { "Location": "https://" + host + req.url });
res.end();
}
function httpsConnection(req, res) {
res.writeHead(200, { 'Content-Length': '5' });
res.end('HTTPS');
}
但是这个也指向“HTTPS”而不是应用程序的主页
最佳答案
以下是我如何部署 Node js 应用程序并进行部署。
-在服务器上安装nginx - 在服务器上安装pm2 -使用pm2启动你的node js服务器。例如:本地主机:3000 -更新nginx配置 o 将所有 http 请求重定向到 https o 使用 proxy_server 将 https 请求转发到 localhost:3000
nginx 配置:
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name example.com;
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name example.com;
ssl_certificate path_to_certificate;
ssl_certificate_key path_to_private_key;
root /usr/share/nginx/html;
location / {
proxy_pass http://localhost:3000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_read_timeout 5m;
proxy_connect_timeout 5m;
proxy_redirect off;
}
...
如果您有任何疑问,请告诉我。
关于javascript - 如何在node.js中将http重定向到https,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58722485/