透過nginx反向代理,就取得不到真實ip,是取得的nginx的ip,要得到真實的IP要進行設定Nginx的設定檔: nginx.conf
proxy_set_header X-Real-IP $remote_addr;
例如:
######################################################################## #要转发地域名: upstream t.csdn.com { server 192.168.1.188:8080 max_fails=0 weight=1; #8080为tomcat端口 } ################################################################## server { listen 80; server_name t.csdn.com; access_log /data/wwwlogs/access_tomcat.log combined; root /usr/local/tomcat/webapps; index index.html index.jsp; #反向代理配置,将所有请求为http://hostname的请求全部转发到upstream中定义的目标服务器中。 location / { #此处配置的域名必须与upstream的域名一致,才能转发。 proxy_pass http://t.csdn.com; proxy_set_header X-Real-IP $remote_addr; } #启用nginx status 监听页面 location /nginxstatus { stub_status on; access_log on; } }
private static String getRemoteAddrIp(HttpServletRequest request) { String ipFromNginx = getHeader(request, "X-Real-IP"); log.info("ipFromNginx:" + ipFromNginx); log.info("getRemoteAddr:" + request.getRemoteAddr()); return StringUtils.isEmpty(ipFromNginx) ? request.getRemoteAddr() : ipFromNginx; } private static String getHeader(HttpServletRequest request, String headName) { String value = request.getHeader(headName); return (StringUtils.isNotBlank(value) && !"unknown" .equalsIgnoreCase(value)) ? value : ""; }
String clientIp = getRemoteAddrIp(request); log.info("客户IP:" + clientIp);
以上就介紹了透過nginx反向代理,Tomcat獲取真實的客戶端IP而非伺服器IP,包括了tomcat,nginx方面的內容,希望對PHP教程有興趣的朋友有所幫助。