首页 > 解决方案 > 使用nodejs将http重定向到https时出现ERR_CONNECTION_REFUSED

问题描述

我正在尝试使用 nodejs 将 http 请求重定向到 https。到目前为止,这是我的代码。我已包含所有密钥、证书等。http 和 https 端口已打开(自定义端口,而不是默认端口)

现在在点击 http 时,网站确实被重定向到 https,但它显示错误,如随附的屏幕截图所示。截图

证书是有效的(见屏幕截图底部),但它仍然说这个页面不安全。

请指导我哪里错了和可能的解决方案。

我在这里搜索过,但无法解决这个问题。谢谢。

   var fs = require('fs');
var http = require('http');
var http_port    =any_port; 
var app = require('express')();

// HTTPS definitions
var https = require('https');
var https_port    =another_port; 
var options = {
    key: fs.readFileSync('example.key'),
    cert:fs.readFileSync('example.crt'),
    ca:  fs.readFileSync('bundleexample.crt')
};

app.get('/', function (req, res) {
   res.end('Hello https World!');
});

https.createServer(options, app).listen(https_port, function () {
   console.log('https port ' + https_port); 
});

// Redirect from http port to https

http.createServer(function (req, res) {
    res.writeHead(301, { "Location": "https://" + req.headers['host'].replace(http_port,https_port) + req.url });
    res.end();
}).listen(http_port);

标签: node.jshttphttpsssl-certificate

解决方案


推荐阅读