Nginx replace REMOTE_ADDR with X-Forwarded-For

后端 未结 4 2005
逝去的感伤
逝去的感伤 2020-12-15 04:57

I am quite new to Nginx, and it seems all so confusing. I have my server setup perfectly, but the problem is, since my server is protected using a HTTP proxy; instead of log

相关标签:
4条回答
  • 2020-12-15 05:37

    An addition to @fredrik's answer.
    It might be better to set $real_ip using map directive:

    map $http_x_forwarded_for $real_ip {
            ~^(\d+\.\d+\.\d+\.\d+) $1;
            default $remote_addr;
        }
    

    Then, set fastcgi_param REMOTE_ADDR in fastcgi_params file or a location block:

    fastcgi_param  REMOTE_ADDR          $real_ip;
    

    edit: Typo fixed in variable name

    0 讨论(0)
  • 2020-12-15 05:42

    The correct way of doing this is by setting the real_ip_header configuration in nginx.

    Example with trusted HTTP proxy IP:

    set_real_ip_from 127.0.0.1/32;
    real_ip_header X-Forwarded-For;
    

    This way, the $_SERVER['REMOTE_ADDR'] will be correctly filled up in PHP fastcgi.

    Documentation link - nginx.org

    0 讨论(0)
  • 2020-12-15 05:47

    I solved my own problem, since PHP gets filtered through FastCGI, I simply added a fast CGI param which set REMOTE_ADDR to the variable http_x_forwarded_for, so something similar to this:

    fastcgi_param REMOTE_ADDR $http_x_forwarded_for;
    
    0 讨论(0)
  • 2020-12-15 05:50

    $http_x_forwared_for might contain multiple ip addresses, where the first one should be the client ip. REMOTE_ADDR should only be the client ip.

    So by using regex in your nginx.conf, you can set REMOTE_ADDR to the first ip of $http_x_forwarded_for like so:

      set $realip $remote_addr;
      if ($http_x_forwarded_for ~ "^(\d+\.\d+\.\d+\.\d+)") {
        set $realip $1;
      }
      fastcgi_param REMOTE_ADDR $realip;
    
    0 讨论(0)
提交回复
热议问题