Nodejs HTTP和HTTPS在同一个端口上

时间:2014-03-17 12:03:05

标签: node.js http express https

我一直在谷歌上搜索stackoverflow,但我找不到我喜欢的答案; - )

我有一个运行在HTTPS和端口3001上的NodeJS服务器。现在我想在端口3001上获取所有传入的HTTP请求,并通过HTTPS将它们重定向到同一个URL。

这一定是可能的。不是吗?

谢谢!

4 个答案:

答案 0 :(得分:70)

如果遵循惯例

,则不需要在同一端口上侦听

按照惯例,当您请求http://127.0.0.1时,您的浏览器将尝试连接到端口80.如果您尝试打开https://127.0.0.1,您的浏览器将尝试连接到端口443.因此,要保护所有流量,只需传统的方式来侦听http上的端口80,重定向到 https ,我们已经有了一个https端口443的监听器。这里是代码:

var https = require('https');

var fs = require('fs');
var options = {
    key: fs.readFileSync('./key.pem'),
    cert: fs.readFileSync('./cert.pem')
};

https.createServer(options, function (req, res) {
    res.end('secure!');
}).listen(443);

// Redirect from http port 80 to https
var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url });
    res.end();
}).listen(80);

使用https进行测试:

$ curl https://127.0.0.1 -k
secure!

使用http:

$ curl http://127.0.0.1 -i
HTTP/1.1 301 Moved Permanently
Location: https://127.0.0.1/
Date: Sun, 01 Jun 2014 06:15:16 GMT
Connection: keep-alive
Transfer-Encoding: chunked

如果您必须在同一端口上侦听

在同一端口上使用http / https监听并不是一种简单的方法。您最好的办法是在一个简单的网络套接字上创建代理服务器,该网络套接字根据传入连接的性质(http与https)进行管道传输(http或https)。

以下是完整代码(基于https://gist.github.com/bnoordhuis/4740141)。它侦听localhost:3000并将其传递给http(后者又将其重定向到https),或者如果incomming连接是https,它只是将其传递给https处理程序

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('./key.pem'),
    cert: fs.readFileSync('./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连接它,则会获得https处理程序:

$ curl https://127.0.0.1:3000 -k
HTTPS

如果你用http连接它,你会得到重定向处理程序(它只是带你到https处理程序):

$ curl http://127.0.0.1:3000 -i
HTTP/1.1 301 Moved Permanently
Location: https://127.0.0.1:3000/
Date: Sat, 31 May 2014 16:36:56 GMT
Connection: keep-alive
Transfer-Encoding: chunked

答案 1 :(得分:16)

我知道这是一个老问题,但只是把它作为别人的参考。 我发现最简单的方法是使用 https://github.com/mscdex/httpolyglot模块。似乎做得非常可靠

    var httpolyglot = require('httpolyglot');
    var server = httpolyglot.createServer(options,function(req,res) {
      if (!req.socket.encrypted) {
      // Redirect to https
        res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url });
        res.end();
      } else {
        // The express app or any other compatible app 
        app.apply(app,arguments);
      }
  });
 // Some port
 server.listen(11000);

答案 2 :(得分:14)

如果通过单个端口提供HTTP和HTTPS是绝对必要的,您可以直接将请求代理到相关的HTTP实现,而不是将套接字传送到另一个端口。

httpx.js



'use strict';
let net = require('net');
let http = require('http');
let https = require('https');

exports.createServer = (opts, handler) => {

    let server = net.createServer(socket => {
        socket.once('data', buffer => {
            // Pause the socket
            socket.pause();

            // Determine if this is an HTTP(s) request
            let byte = buffer[0];

            let protocol;
            if (byte === 22) {
                protocol = 'https';
            } else if (32 < byte && byte < 127) {
                protocol = 'http';
            }

            let proxy = server[protocol];
            if (proxy) {
                // Push the buffer back onto the front of the data stream
                socket.unshift(buffer);

                // Emit the socket to the HTTP(s) server
                proxy.emit('connection', socket);
            }
            
            // As of NodeJS 10.x the socket must be 
            // resumed asynchronously or the socket
            // connection hangs, potentially crashing
            // the process. Prior to NodeJS 10.x
            // the socket may be resumed synchronously.
            process.nextTick(() => socket.resume()); 
        });
    });

    server.http = http.createServer(handler);
    server.https = https.createServer(opts, handler);
    return server;
};
&#13;
&#13;
&#13;

example.js

&#13;
&#13;
'use strict';
let express = require('express');
let fs = require('fs');
let io =  require('socket.io');

let httpx = require('./httpx');

let opts = {
    key: fs.readFileSync('./server.key'),
    cert: fs.readFileSync('./server.cert')
};

let app = express();
app.use(express.static('public'));

let server = httpx.createServer(opts, app);
let ws = io(server.http);
let wss = io(server.https);
server.listen(8080, () => console.log('Server started'));
&#13;
&#13;
&#13;

答案 3 :(得分:-1)

如果它是纯粹的Node.JS HTTP模块,那么你可以试试这个:

if (!request.connection.encrypted) { // Check if the request is not HTTPS
    response.writeHead(301, { // May be 302
        Location: 'https://' + YourHostName + ':3001' + request.url
        /* Here you can add some more headers */
    });

    response.end(); // End the response
} else {
    // Behavior for HTTPS requests
}