nginx反向代理获取用户真实Ip地址
nginx做反向代理时,默认的配置后端获取到的Ip地址都来自于nginx,用request.getRemoteAddr();获取到的是nginx的ip地址,而不是用户的真实ip.
1.修改Nginx配置:
server {
listen 80;
server_name jenkins.local.com;
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 java.net.InetAddress;
import java.net.UnknownHostException;
public class HttpUtils {
public static String getRealIp(HttpServletRequest request){
String ip;
if (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 = InetAddress.getLocalHost().getHostAddress();
}catch (Exception e){
e.printStackTrace();
}
}
return ip;
}
}
|