Skip to content

CodeCraft Hub

Obtaining Real Client IP in Nginx Reverse Proxy to Node.js Server

DevOps, Server1 min read


Hello! Today, let's explore how to obtain the real client IP address in an Nginx reverse proxy setup forwarding requests to a Node.js server. To understand this process, let's first glance at the relationships between the Load Balancer (LB), Nginx reverse proxy, and the Node.js server.

Scenario Overview

Load Balancer (LB): A device distributing traffic from clients to multiple servers. LB typically has a unique IP address. (e.g.,

Nginx Reverse Proxy: An intermediate server forwarding requests received from the Load Balancer to various servers. This server can encapsulate the client's IP address while sending responses. (e.g., 456.456.456.456)

Node.js Server: The actual server where the web application operates.

Nginx Configuration

Now, let's dive into the actual configuration. Add the following settings related to set_real_ip_from in the Nginx configuration file.

  1. set_real_ip_from;
    This configuration informs Nginx that the IP address of the load balancer is a trusted source. By setting this, Nginx only allows requests from this address, ensuring that it trusts it as a reliable source for obtaining the actual client's IP.

  2. real_ip_header X-Forwarded-For;
    This setting instructs Nginx to use the X-Forwarded-For header to identify the real client IP address. This header contains a list of IP addresses sent from the client to the server.

  3. real_ip_recursive on;
    This configuration allows Nginx to select the first IP address when there are multiple IP addresses in the X-Forwarded-For header. This ensures that the actual client's IP address is trusted.

Obtaining Real Client IP

Now, let's see how to retrieve the real client IP in the Node.js server.


Congratulations! You've successfully configured Nginx reverse proxy to effectively obtain the real client IP address. Thank you! After applying the configuration, remember to reload Nginx or restart it to ensure the changes take effect.

Note that when restarting Nginx, it's advisable to use nginx -t (configuration file syntax test) first and then use reload to restart. Unlike restart, reload reads the configuration file again. Even if there are issues, the web server won't shut down, maintaining its current state.

© 2024 by CodeCraft Hub. All rights reserved.
Powered by Gatsby