Remote Ip Address Trace With Nginx From Spring Boot
Posted By : Md Imroz Alam | 21-May-2018
Nginx is a fast and reliable server with low memory consumption. When we configure our spring boot application with a reverse proxy in Nginx configuration. we unable to exact IP address of the remote client. it shows 127.0.0.1 or same IP address of deployed server due to reverse proxy.
Following are configuration with Nginx
server {
listen 80 default_server;
server_name example.com;
location / {
proxy_set_header X-Forwarded-Host $host:$server_port;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
}
X-Forwarded-Host:- It gives us client request port number.
X-Forwarded-Server:- It gives us client hostname.
X-Forwarded-For:- It gives us client exact IP address.
we simply get the IP address by request.getHeader("X-Forwarded-For") of HttpServeletRequest. this code statement, the IP address are separated by "," delimiter first entry will be exact IP address.
Following is code for a spring-boot application
@RequestMapping(value = "/get/ipaddress", method = RequestMethod.GET)
Object IPAddress(HttpServletRequest request) {
Map<String,Object> result = new HashMap<String, Object>();
try {
String remoteAddress="";
if (request != null) {
remoteAddress = request.getHeader("X-Forwarded-For");
if (remoteAddress == null || "".equals(remoteAddress)) {
remoteAddress = request.getRemoteAddr();
}
}
remoteAddress=remoteAddress!=null && remoteAddress.contains(",")
? remoteAddress.split(",")[0]
: remoteAddress;
LOGGER.info("remote ip addres {}",remoteAddress);
result.put("ipAddress",remoteAddress);
return ResponseHandler.generateResponse(HttpStatus.OK, true, "Success", result);
} catch (Exception e) {
return ResponseHandler.generateResponse(HttpStatus.INTERNAL_SERVER_ERROR, false, e.getMessage(), result);
}
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Md Imroz Alam
Md. Imroz Alam is a bright Web App Developer, he has good knowledge of Java, J2SE, Jsp, Servlet, jdbc. His hobbies are watching movie, playing carom.