nginx reverse proxy obtains the real ip of users

When nginx is used as the reverse proxy, the ip obtained by the default configuration backend is from nginx. How to forward the user's real ip to the backend program? For example, in java backend, use request.getRemoteAddr(); obtain the nginx ip address, not the user's real ip address

Modify nginx configuration as follows:

upstream {

server {
    location / {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

After adding the following three instructions to the original configuration, you can use request.getHeader("X-Forwarded-For"); to get the ip address of the visitor

Appendix: the implementation of getting client ip by Java

private static final String[] IP_HEADER_CANDIDATES = {
    "REMOTE_ADDR" };

public static String getClientIpAddress(HttpServletRequest request) {
    for (String header : IP_HEADER_CANDIDATES) {
        String ip = request.getHeader(header);
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            return ip;
    return request.getRemoteAddr();

Reference resources

  1. nginx reverse proxy obtains the real ip of users
  2. How to configure nginx to obtain the real IP address of users
  3. How to get Client IP Address using Java
  4. Getting IP address of client

Keywords: Nginx Java

Added by Owe Blomqvist on Mon, 23 Dec 2019 19:47:17 +0200