Before going into the details about the reverse proxy, let’s understand the proxy first.
What is a proxy?
It's a server that sits in front of a client machine(s). Its main purpose is to protect the client's identity for outgoing requests to the internet and to give controlled access to the content. Basically it acts as a middle man for those clients.
What is a reverse proxy?
Similarly, reverse proxy is the same as a proxy but it does the opposite of proxy. It sits in front of the server(s) and intercept the incoming requests.
Let's go ahead and configure the NGINX as a reverse proxy for the server. In our case we are configuring it for the server running in Node.js on port 3000.
This is how our NGINX configuration would look like.
The default nginx.conf
file.
Our custom configuration file, lets call it app.conf
Make sure to install the nginx-extras
from the respective package manager's like yum, apt-get etc
In the default nginx.conf
, we added following lines
include /etc/nginx/modules-enabled/*.conf;
- which will load all the enabled modules.- Added custom
log_format
In app.conf
configuration file
- The first 3 lines,
set_real_ip_from 10.0.0.0/16;
real_ip_header x-forwarded-for;
real_ip_recursive on;
- this will set the client real IP from thex-forwarded-for
header. (This is required if its placed behind the AWS ALB, use appropriate VPC CIDR instead of 10.0.0.0/16) limit_req_zone $remote_addr zone=web_reqs_1:30m rate=5r/s;
- to apply rate limit in general or to certain url path. This is applied only when you definelimit_req zone=web_reqs_1 burst=10 delay=5;
inside the server block or location block. In this case, it will allow only 5 requests per second per client IP.-
add_header
in location block - add custom header to the outgoing response. server_tokens off;
- Hide NGINX build name and its version from the response header.more_clear_headers 'ETag' 'Server' 'X-Powered-By' 'X-Runtime' 'X-Nextjs-Cache';
- Removes mentioned headers from the response.
What are the benefits of reverse proxy?
- It can act as a load balancer. In this scenario, its main purpose is to direct the traffic to the appropriate app server by distributing the load evenly among them.
- It can be used for caching static assets like JS/CSS or images.
- It can protect server identities by hiding certain response headers.
- It can be used to protect app servers from external attacks like DDoS, either by rate limiting or completely blocking certain IP addresses.
- It can be used to set custom HTTP headers for the outgoing response.
- It can be used to make site or part of the site private by enabling the basic authentication.
- It can also be used to get the location information (like City, State, Country etc) of the client by their IP address.
Overall it would be good to have NGINX before the app server to intercept the requests, even if you have a proper load balancing solutions like AWS ALB.