nginx获取真实的ip的方法
作者:广铁小多多
在实际应用中,我们可能需要获取用户的ip地址,比如做异地登陆的判断等等,本文主要介绍了nginx获取真实的ip的方法,具有一定的参考价值,感兴趣的可以了解一下
我这里使用是springboot项目,使用nginx做代理,但header里面的参数没有将ip带过来,所有需要配置nginx将ip带过来。
nginx.conf文件
server { listen 80; listen 443 ssl; server_name xxx.xxx.com; ssl_certificate /web/project/ai-master/ssl/xxx.xxx.com_bundle.pem; ssl_certificate_key /web/project/ai-master/ssl/xxx.xxx.com.top.key; #接口 location /api { #保留代理之前的host 包含客户端真实的域名和端口号 proxy_set_header Host $host; #保留代理之前的真实客户端ip proxy_set_header X-Real-IP $remote_addr; #这个Header和X-Real-IP类似,但它在多级代理时会包含真实客户端及中间每个代理服务器的IP proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #表示客户端真实的协议(http还是https) proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://aiMasterServer/api; } }
RequestUtil.java文件
/** * @Description:请求处理类 * @author: Adobe Chow * @date: 2019/4/25 10:42 * @Copyright: www.winshang.com Inc. All rights reserved. */ public class RequestUtil { public static HttpServletRequest getRequest(){ HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); return request; } public static HttpServletResponse getResponse(){ HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse(); return response; } /*** * 获取客户端IP地址;这里通过了Nginx获取;X-Real-IP, * @return */ public static String getClientIP() { HttpServletRequest request = getRequest(); String ip = request.getHeader("X-Real-IP"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 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; } }
到此这篇关于nginx获取真实的ip的方法的文章就介绍到这了,更多相关nginx获取真实ip内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!