This tutorial will show you how to use Mongoose to implement a reverse proxy

We'll have two connections, as seen in the graph

** GRAPH **

  • C1 is the usual connection from the outside world, where we are an HTTP server
  • C2 is the new connection to the backend server, where we are an HTTP client.

We'll then need two callback functions, one to handle the requests from the client, as seen on the http-server tutorial, and the other to handle responses from the backend server, as seen on the http-client tutorial.

All requests from the client will be forwarded to the backend server, though we'll re-write the "Host" header in the process. We'll write a convenient function for that.

All responses from the backend server will be forwarded to the client.

Build and run

  • If you've not already done so, clone the Mongoose Library repo
    $ git clone https://github.com/cesanta/mongoose
  • Build the example, this will also start Mongoose:
    $ cd mongoose/examples/http-reverse-proxy
    $ make clean all
  • Go to http://localhost:8000 in your browser; you'll see the very first web page at CERN

Build with TLS support

The makefile will take care of this, just pass it the proper argument.

  • For openSSL:
    $ make clean all SSL=OPENSSL
  • For mbedTLS:
    $ make clean all SSL=MBEDTLS
  • Go to http://localhost:8000 in your browser; you'll see Cesanta's web page

For more information on building TLS clients, check the TLS tutorial

How it works

  • For each incoming request, we create a new backend connection, and pass parameter fn_data to point to the connection to the outside world, so its handler is able to forward the backend response.

    We also signal this connection has to close once we receive a closure indication. Note also that we initialise TLS if the backend server URL is `https://`.
  • Over this new connection, we forward the client request, rewriting the "Host" header:

  • The backend connection handler receives data from the backend server and writes it into the connection to the client

    It also disconnects once it receives a closure indication

Browse latest code