nginx反向代理获取ip,java获取真实ip。需求是,前端vue跟java项目,部署到阿里云服务器后,vue运行在nginx中,需要通过java获取nginx代理后,用户客户端的ip,我本机的ip是
java代码是,
```java
/**
*/
@PostMapping("/sendTask")
public String sendTask(@RequestBody TaskRequest request, HttpServletRequest servletRequest) {
try {
// 测试内容
/* InetAddress localHost = InetAddress.getLocalHost();
String localIpAddress = localHost.getHostAddress();
System.out.println("本地 IP 地址: " + localIpAddress);*/
String localIpAddress = getClientIp(servletRequest);
log.info("客户端 IP 地址3: " + localIpAddress);
return "Task sent successfully";
} catch (Exception e) {
e.printStackTrace();
return "Error sending task";
}
}
public String getClientIp(HttpServletRequest request) {
// 打印所有可能来源的 IP 信息
String xForwardedFor = request.getHeader("X-Forwarded-For");
String xRealIp = request.getHeader("X-Real-IP");
String remoteAddr = request.getRemoteAddr();
System.out.println("X-Forwarded-For: " + xForwardedFor);
System.out.println("X-Real-IP: " + xRealIp);
System.out.println("RemoteAddr: " + remoteAddr);
// 检查 X-Forwarded-For 头
if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
// 若有多个 IP(多个代理),取第一个
String[] forwardedIps = xForwardedFor.split(",");
String clientIpFromXForwardedFor = forwardedIps[0].trim();
System.out.println("使用 X-Forwarded-For 提取到的客户端 IP: " + clientIpFromXForwardedFor);
return clientIpFromXForwardedFor;
}
// 检查 X-Real-IP 头
if (xRealIp != null && !xRealIp.isEmpty()) {
System.out.println("使用 X-Real-IP 提取到的客户端 IP: " + xRealIp);
return xRealIp;
}
// 最后使用 request.getRemoteAddr()
System.out.println("使用 RemoteAddr 提取到的客户端 IP: " + remoteAddr);
return remoteAddr;
}
但是打印出来的ip地址是错的,图片如下,
nginx的配置是
```bash
#user nobody;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
log_format debug '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" "$http_x_real_ip"';
access_log /var/log/nginx/access.log debug;
client_max_body_size 10m;
sendfile on;
keepalive_timeout 65;
# 后台代理配置
server {
listen 9999;
location / {
proxy_pass http://127.0.0.1:18881; # 转发规则
proxy_set_header Host $host; # 保持主机头信息一致
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
# 前端接口映射
server {
listen 80;
# 主页面配置
location / {
root dist;
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
# 后端接口配置
location /prod-api/ {
proxy_pass http://127.0.0.1:9999/; # 转发规则
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
现在大概问题我知道在哪里,是在nginx配置里面,有哪位兄台帮忙下,如何把nginx.conf配置一下,让java获取到用户端的ip