nginx proxy tomcat can not get the real ip address solution

nginx proxy tomcat can not get the real ip address solution

May 27, 2016 11:04:06

Number of readings: 2205

This article introduces the solution to the inability to obtain the real ip address when the nginx server is proxying the tomcat system. For those who need it, please refer to it.

 

 

When nginx is proxying tomcat, the client obtained by tomcat is not the ip sent by the client.
Reason analysis:
As a proxy server, nginx first intercepts the request sent by the client, and then forwards it to tomcat as localhost for processing.

Solution:
Add to the location node in the nginx configuration: 
 

Copy code Code example:

proxy_set_header Host $host; 
proxy_set_header X-Real-IP $remote_addr; 
proxy_set_header REMOTE-HOST $remote_addr; 
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Get the remote ip address in java like this:
 

Copy code Code example:

public static String getIpAddr(HttpServletRequest request) {  
 String ip = request.getHeader("x-forwarded-for");  
 if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
     ip = request.getHeader("Proxy-Client-IP");  
 }  
 if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
     ip = request.getHeader("WL-Proxy-Client-IP");  
 }  
 if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
     ip = request.getRemoteAddr();  
 }  
 return ip;  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325813168&siteId=291194637