0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

HTTP, WebSocket混在のプロキシサーバに個別の証明書を適用する方法(node-http-proxy)

Posted at

タイトル通りです

自作アプリ内でHTTPとWebSocketのリクエストをnode-http-proxyのプロキシサーバで振り分けていて、HTTPにしか証明書を適用しなくても動いていたのが、いつからか動かなくなった(Appleのポリシー変更?)ため、対応した内容を書きます。

ネットにある情報で上手くいかなくて苦労しましたが、
肝心なのはSNICallbackの第二引数で制御することでした

後はコードでご確認ください

var httpProxy = require('http-proxy');
var https = require('https');
var tls = require("tls");
var fs = require('fs');

var normalProxy = new httpProxy.createProxyServer({
    target: {
        host: 'localhost',
        port: 8080,
    }
});

var webSocketProxy = new httpProxy.createProxyServer({
    target: {
        host: 'localhost',
        port: 3000,
    }
});

var certs = {
	  "exsample.com": tls.createSecureContext({
                  key: fs.readFileSync('xxx.key', 'utf8'),
                  cert: fs.readFileSync('xxx.cer', 'utf8'),//fullchain
		        }),
	  "ws.exsample": tls.createSecureContext({
		          key: fs.readFileSync('xxx.key', 'utf8'),
		          cert: fs.readFileSync('xxx.cer', 'utf8'),//fullchain
		    })
};

var options = {
    SNICallback: function(hostname, cb){
        var ctx = certs[hostname];
        //このif文が必要だった
        if (cb) {
           cb(null, ctx);
        } else {
           return ctx;
        }
    },
    hostnameOnly: true,
	key: fs.readFileSync('xxx.key', 'utf8'),
	cert: fs.readFileSync('xxx.cer', 'utf8'),

};

var server = https.createServer(options, function(req, res) {
    
    if (req.headers.host == 'exsample.com') {
        normalProxy.web( req, res );
    } else if (req.headers.host == 'ws.exsample') {
        webSocketProxy.web( req, res );
    } else {
        res.writeHead(404);
        res.end();
        return;
    }

});

server.on( 'upgrade', function( req, socket, head ) {
    webSocketProxy.ws( req, socket, head );
});

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?