DEV Community

Rudra Pratap
Rudra Pratap

Posted on

What is NGINX and how reverse proxies work?

Every domain name resolves to a unique IP address.
For example: www.gooogle.com is mapped to 142.250.191.78 ipv4.

Whenever you host your program (for example: nodejs server or php server) on a remote machine (for example: AWS EC2 instances or Digitalocean), you are given a reserved public IP address with which you can connect with that remote device through SSH Terminal or any SSH client like PuTTY.

Now, suppose you visit www.google.com/maps. When you hit enter, your request is sent to the unqiue server which has the IP address 142.250.191.78. Now your request has reached to the correct device, but how does /maps goes to the correct program running inside that device? Suppose you want that every www.google.com/maps must be served by a Nodejs server running inside that EC2 instance and www.google.com/docs must be served by a PHP server. How can we forward the /maps request to Nodejs server and /docs request to PHP server?


Image description

In the above diagram it is clearly shown that multiple requests are resolved by different app servers inside our machine.
For example: /maps can be served by a Nodejs server, /docs can be served by a PHP server etc.

Solution
This is done by NGINX server which is installed on the physical machine.

NGINX maps the incoming request to be resolved by some other backend server. This process is called reverse proxy.

A reverse proxy server is a type of proxy server that typically sits behind the firewall in a private network and directs client requests to the appropriate backend server.

An other popoular proxy server is HAproxy.

Now I am diving deep into the topic, so be attentive.
First of all let me make a quote.

By default, all HTTP requests are served on port 80.
By default, all HTTPS requests are served on port 443.

Let suppose your /maps request is to be served by a Node server listening on port 1234 and your /docs request is to be servered by a PHP server on port 1235.

Now any request coming from client in the form of /maps or /docs, carries a default port 80 if it is an http request and 443 if it is an https request.

So, we must map the incoming request to different ports, which is done by NGINX.

Following image illustrates the process:

Image description

NGINX is written in C and it is very performant. It can handle ~10000 concurrent requests!
It can do multiple things like:

  • Load balancing
  • Rate limiting
  • Http caching
  • Reverse proxy
  • Websocket connection
  • Handling of static files, index files, and auto-indexing.
  • URL redirection and rewriting...

Following image illustrates the load balancing part:

Image description

Thanks, please upvote.

Top comments (0)