nginx代理web服务后如何获取客户端的真实ip
问题描述
如果用户直接访问web服务,可以通过如下方式获取到客户端ip:
String clientIp1 = request.getRemoteAddr();
如果使用nginx代理web服务,通过上述方式获取到的IP地址为nginx的地址。
解决办法
nginx配置修改
在nginx中添加如下配置:
proxy_set_header X-Real-IP $remote_addr;
jsp代码修改
在jsp中使用以下方式,即可获取到客户端的实际ip:
String clientIp2 = request.getHeader("X-Real-IP");
修改后,可以通过nginx获取到客户端的真实ip:
完整代码
nginx配置
# test-nginx-config
upstream ip_server {
ip_hash;
server 127.0.0.1:8080;
}
server {
listen 9001;
#listen localhost:8080;
#server_name somename alias another.alias;
location /ip/{
proxy_pass http://ip_server;
#Proxy Settings
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 60;
proxy_read_timeout 60;
proxy_send_timeout 60;
}
}
jsp代码
<%@ page language="java" pageEncoding="utf-8"%>
<html>
<head><title>test ip</title></head>
<body>
<h1><font color="blue">Client Info</h1>
<table align="centre" border="1">
<tr>
<td>Session ID</td>
<% session.setAttribute("my.name","zhangSan"); %>
<td><%= session.getId() %></td>
</tr>
<tr>
<td>Server IP</td>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getLocalAddr() +":"+request.getLocalPort()+path+"/";
String clientIp1 = request.getRemoteAddr();
String clientIp2 = request.getHeader("X-Real-IP");
%>
<td><%=basePath%></td>
</tr>
<tr>
<td>Created on</td>
<td><%= session.getCreationTime() %></td>
</tr>
<tr>
<td>Ip from Web</td>
<td><%= clientIp1 %></td>
</tr>
<tr>
<td>Ip from Nginx</td>
<td><%= clientIp2 %></td>
</tr>
</table>
</body>
</html>