How does nginx do reverse proxy load balancing Java how to get the backend server to get the user IP

Nginx does reverse load balancing, and the backend server obtains the real client ip

First, the following configuration needs to be done on the front-end nginx :

location /

proxy_set_hearder host                $host;

proxy_set_header X-forwarded-for $proxy_add_x_forwarded_for;

proxy_set_header X-real-ip           $remote_addr;

};

nginx will replace the ip address in the http header before forwarding the request to the background real-server; after this operation is completed, the real-server also needs to do some operations;

 

public class ClientIPUtils {
 /**
  * In many applications, it may be necessary to record the user's real IP address. At this time, the user's real IP address must be obtained. In JSP, the method to obtain the client's IP address
  * is: request.getRemoteAddr(), this method is valid in most cases. However, after passing through Apache, Squid and other
  reverse proxy software, the real IP address of the client cannot be obtained.
  * However, X-FORWARDED-FOR information is added to the HTTP header information of the forwarding request. Used to track the original client IP address and the server address requested by the original client.
  * @param request
  * @return
  */

public static String getClientIp(HttpServletRequest request) {

           String ip = request.getHeader("x-forwarded-for");

     //String ip = request.getHeader("X-real-ip");

            logger.debug("x-forwarded-for = {}", ip);
           if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
               ip = request.getHeader("Proxy-Client-IP"); 
               logger.debug("Proxy-Client-IP = {}", ip); 
           }
           if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
               ip = request.getHeader("WL-Proxy-Client-IP");
               logger.debug("WL-Proxy-Client-IP = {}", ip);
           }
           if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
               ip = request.getRemoteAddr();
               logger.debug("RemoteAddr-IP = {}", ip); 
           }
           if(StringUtils.isNotBlank(ip)) {
               ip = ip.split(",")[0];
           }
           return ip;

       }

}

Guess you like

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