Obtaining the Client’s Real IP after Nginx Reverse Proxy
When a client accesses a web application through a reverse proxy server like Nginx, the client’s real IP address is not directly available to the web application. This is because the client’s requests are forwarded to the web application through the reverse proxy server, which masks the client’s IP address.
The Problem
After Nginx reverse proxy, the request.getRemoteAddr() method returns the IP address of Nginx, not the client’s real IP address. Similarly, the request.getRequestURL() method returns the domain name, protocol, and port of Nginx, not the client’s real domain name, protocol, and port. This is because the client’s requests are not directly connected to the web application, but are instead routed through the reverse proxy server.
Solving the Problem
To solve this problem, we need to configure the reverse proxy server (Nginx) to pass the client’s information to the web application (Tomcat). We can do this by adding some HTTP headers to the requests forwarded by Nginx to Tomcat.
Configuring Nginx
We need to add the following configuration to each location of the agent:
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
This configuration adds the following headers to the requests forwarded by Nginx to Tomcat:
Host: contains the client’s real domain name and port number.X-Real-IP: indicates the client’s real IP address.X-Forwarded-Proto: indicates the client’s real protocol (http or https).X-Forwarded-For: includes the real IP client and the middle of each proxy server.
Configuring Tomcat
After configuring Nginx, we still need to configure Tomcat to obtain the client’s real IP address. We can do this by adding a RemoteIpValve to the server.xml file of Tomcat:
<Valve className="org.apache.catalina.valves.RemoteIpValve" />
This valve will allow Tomcat to obtain the client’s real IP address from the X-Real-IP header passed by Nginx.
A More Elegant Solution
Alternatively, we can use the RemoteIpValve to obtain the client’s real IP address without relying on the X-Real-IP header. We can configure the RemoteIpValve to use the X-Forwarded-For header instead:
<Valve className="org.apache.catalina.valves.RemoteIpValve" />
This will allow Tomcat to obtain the client’s real IP address from the X-Forwarded-For header passed by Nginx.
Conclusion
In conclusion, obtaining the client’s real IP address after Nginx reverse proxy requires configuring both the reverse proxy server (Nginx) and the web application (Tomcat). By adding some HTTP headers to the requests forwarded by Nginx to Tomcat, we can pass the client’s information to the web application. We can then use the RemoteIpValve to obtain the client’s real IP address from the headers passed by Nginx.