欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

tomcat 获取Nginx的真实用户IP

程序员文章站 2024-01-26 19:53:22
...
需要:添加 proxy_set_header X-Real-IP $remote_addr;

upstream tomcat_server { 
            server localhost:8080 weight=1;
    } 

    server {
        listen       80;
        server_name 192.168.40.116;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

	location ~* "\.(jsp|do)$" { #当请求的是jsp或do文件时直接到tomcat上去取
     	 	#root  html;
      	 	#index index.html index.htm;
         	#proxy_pass http://192.168.18.201/;
          	proxy_pass http://tomcat_server;
		client_max_body_size     2048m;
       		client_body_buffer_size  128k;
       		proxy_connect_timeout    600;
       		proxy_read_timeout       600;
       		proxy_send_timeout       6000;
       		proxy_buffer_size        16k;
       		proxy_buffers            64k;
       		proxy_busy_buffers_size 64k;
       		proxy_temp_file_write_size 64k;
        }

        location / {
           #发布目录/data/www 
        #    root   /home/ding/ITsoftware/tomcat/webapps/100mshCloud;
	#   fastcgi_pass   192.168.40.116:8080;
  	   proxy_set_header  X-Real-IP  $remote_addr;  
 	   proxy_pass http://tomcat_server/; #注释默认两行,新增一行。
        #    index  index.html index.htm;
        }
tomcat 获取:

public static String getRemoteAddrIp(HttpServletRequest request) {  
    String ipFromNginx = getHeader(request, "X-Real-IP");  
    System.out.println("ipFromNginx:" + ipFromNginx);  
    System.out.println("getRemoteAddr:" + request.getRemoteAddr());  
    return StringUtil.isEmpty(ipFromNginx) ? request.getRemoteAddr() : ipFromNginx;  
}  
  
  
private static String getHeader(HttpServletRequest request, String headName) {  
    String value = request.getHeader(headName);  
    return !StringUtils.isBlank(value) && !"unknown".equalsIgnoreCase(value) ? value : "";  
}  

以上就介绍了tomcat 获取Nginx的真实用户IP,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。