Search code examples
node.jshttp-proxy

Node.js http-proxy allow HTTPS


I have an application that creates a proxy server and returns the url requests when a page is accessed, but it works only for http web pages and when I'm trying to access a https address then I get Secure Connection Failed in the browser.

To solve this, I generated a Self-Signed Certificate for localhost:8080 from here, but still can't access secured web pages...

This is my code:

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

var proxy = httpProxy.createServer({
  ssl: {
    key:  fs.readFileSync('ssl_key_8080.pem', 'utf8'),
    cert:  fs.readFileSync('ssl_cert_8080.pem', 'utf8')
  },
  target:'https://localhost:8080',
  secure: true
});

proxy.listen(443);

var http = require('http');

http.createServer(function (req, res) {
  var options = {
    target: 'http://' + req.headers.host,
  };
  req.host = req.headers.host;
  proxy.web(req, res, options, function(err){
    console.log('err', err)
  });
}).listen(8080);

proxy.on('proxyReq', function (proxyReq, req, res) {
  console.log('request url', JSON.stringify(req.url, true, 2));
});

Is there something that I'm not doing right? I followed the instructions from http-proxy docs


Solution

  • The issue is you have a self signed certificate and you are using the secure flag in the proxy settings object, from the docs

    You can activate the validation of a secure SSL certificate to the target connection (avoid self signed certs), just set secure: true in the options.

        var proxy = httpProxy.createServer({
      ssl: {
        key:  fs.readFileSync('ssl_key_8080.pem', 'utf8'),
        cert:  fs.readFileSync('ssl_cert_8080.pem', 'utf8')
      },
      target:'https://localhost:8080',
      secure: true
    });
    

    If you remove the secure flag, you might get an error in your browser that the route isn't safe.

    In the context of your code.

    var httpProxy = require('http-proxy');
    var fs = require('fs');
    
    var proxy = httpProxy.createServer({
      ssl: {
        key:  fs.readFileSync('ssl_key_8080.pem', 'utf8'),
        cert:  fs.readFileSync('ssl_cert_8080.pem', 'utf8')
      },
      target:'https://localhost:8080'
    });
    
    proxy.listen(443);
    
    var http = require('http');
    
    http.createServer(function (req, res) {
      var options = {
        target: 'http://' + req.headers.host,
      };
      req.host = req.headers.host;
      proxy.web(req, res, options, function(err){
        console.log('err', err)
      });
    }).listen(8080);
    
    proxy.on('proxyReq', function (proxyReq, req, res) {
      console.log('request url', JSON.stringify(req.url, true, 2));
    });