JDK版本:17.0.5
Open-Resty版本(Nginx改版):1.25.3.1
nginx配置:
location /prod-api {
# 允许最大10MB的文件上传
client_max_body_size 10M;
proxy_pass http://{反射到内部的IP/域名}:{反射到内部的接口};
rewrite /prod-api/(.*) /$1 break;
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_set_header X-Forwarded-Proto $scheme;
}
java代码:
// import jakarta.servlet.http.HttpServletRequest;
// import org.springframework.web.bind.annotation.GetMapping;
// import org.springframework.web.bind.annotation.RestController;
@GetMapping("/getIp")
public String getIp(HttpServletRequest request) {
String remoteAddr = "";
if (request != null) {
remoteAddr = request.getHeader("X-FORWARDED-FOR");
if (remoteAddr == null || remoteAddr.isEmpty()) {
remoteAddr = request.getRemoteAddr();
}
}
return remoteAddr;
}