Nodejs HTTP和HTTPS在同一个端口上

use*_*996 37 https http node.js express

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

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

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

谢谢!

bas*_*rat 71

如果遵循惯例,则无需在同一端口上侦听

按照惯例,当您请求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);
Run Code Online (Sandbox Code Playgroud)

使用https进行测试:

$ curl https://127.0.0.1 -k
secure!
Run Code Online (Sandbox Code Playgroud)

用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
Run Code Online (Sandbox Code Playgroud)

如果你必须在同一个端口上听

没有简单的方法让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');
}
Run Code Online (Sandbox Code Playgroud)

作为测试,如果您使用https连接它,您将获得https处理程序:

$ curl https://127.0.0.1:3000 -k
HTTPS
Run Code Online (Sandbox Code Playgroud)

如果你用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
Run Code Online (Sandbox Code Playgroud)


Pra*_*pal 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);
Run Code Online (Sandbox Code Playgroud)


Jak*_*ger 15

如果在单个端口上提供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;
};
Run Code Online (Sandbox Code Playgroud)

example.js

'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'));
Run Code Online (Sandbox Code Playgroud)


mic*_*nic -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
}
Run Code Online (Sandbox Code Playgroud)