java获取nginx反向代理的客户端真实ip(非服务器ip)
在使用nginx方向代理后
Remote Address代表的就是服务器的ip地址,而不是客户端的ip地址了,想要获取真实ip,就需要在nginx里面配置
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $http_x_forwarded_for - $http_x_real_ip'; access_log logs/access.log main; sendfile on; keepalive_timeout 65; upstream tomcat_server_pool{ #server 172.17.0.14:3000 weight=10; #server 172.17.0.14:3001 weight=10; server 127.0.0.1:1001 weight=10; } server { listen 80; server_name localhost; location / { proxy_pass http://tomcat_server_pool; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; root html; index index.html index.htm; } } }
其中X-Real-IP和X-Forwarded-For都是客户端真实地址
当nginx配置好的后,接下来需要在java中进行获取
public void login(HttpServletRequest request, Model model) { String remoteHost = request.getRemoteHost(); String clientIp = request.getHeader(x-forwarded-for); log.info(clientIp:{},clientIp); String proxyClientIP = request.getHeader(Proxy-Client-IP); log.info(proxyClientIP:{},proxyClientIP); String xRealIP = request.getHeader(X-Real-IP); log.info(xRealIP:{},xRealIP); String host = request.getHeader(Host); log.info(host:{},host); String remoteAddr = request.getRemoteAddr(); log.info(remoteAddr:{},remoteAddr); model.addAttribute(year, TimeUtils.getYear()); queryIp.judgeIp(model, remoteHost, request.getLocalAddr()); }
结果
nginx相关命令
/usr/local/webserver/nginx/sbin/nginx -s reload # 重新载入配置文件 /usr/local/webserver/nginx/sbin/nginx -s reopen # 重启 Nginx /usr/local/webserver/nginx/sbin/nginx -s stop # 停止 Nginx