1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > nginx反向代理获取用户真实Ip地址

nginx反向代理获取用户真实Ip地址

时间:2024-02-25 18:06:49

相关推荐

nginx反向代理获取用户真实Ip地址

nginx反向代理获取用户真实Ip地址

nginx做反向代理时,默认的配置后端获取到的Ip地址都来自于nginx,用request.getRemoteAddr();获取到的是nginx的ip地址,而不是用户的真实ip.

1.修改Nginx配置:

server {listen 80;server_name ;location / {proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_pass http://192.168.10.204:8899; }error_page 500 502 503 504 /50x.html;location = /50x.html {root html;index index.html index.htm index.jsp index.action default.html;}proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}

在原来的基础配置上加上后三行配置,就可以使用request.getHeader(“x-forwarded-for”)来获取用户真实的Ip地址了

2.java获取客户端Ip

package com.zimax.cqyf.admin.util;import javax.servlet.http.HttpServletRequest;import .InetAddress;import .UnknownHostException;/*** http工具类*/public class HttpUtils {/*** 获取真实的ip* @param request* @return* @throws UnknownHostException*/public static String getRealIp(HttpServletRequest request){String ip;// 有的user可能使用代理,为处理用户使用代理的情况,使用x-forwarded-forif (request.getHeader("x-forwarded-for") == null) {ip = request.getRemoteAddr();} else {ip = request.getHeader("x-forwarded-for");}if ("127.0.0.1".equals(ip)) {try {// 获取本机真正的ip地址ip = InetAddress.getLocalHost().getHostAddress();}catch (Exception e){e.printStackTrace();}}return ip;} }

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。