HTTP Reverse Proxy
Overview
This tutorial will show you how to use Mongoose to implement a reverse proxy
We'll have two connections, as seen in the 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
- Follow the Build Tools tutorial to setup your development environment.
- Start a terminal in the project directory; 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/tutorials/http/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
Check the "How to build" section of the TLS tutorial for specific information on building options for your OS
- Go to
http://localhost:8000
in your browser; you'll see Cesanta's web page
For more information on developing TLS clients, check the TLS tutorial
How it works
For each incoming request, we create a new backend connection, and pass parameter
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://`.fn_data
to point to the connection to the outside world, so its handler is able to forward the backend response.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