Set REMOTE_ADDR to X-Forwarded-For in apache

前端 未结 9 1091
感情败类
感情败类 2020-12-29 10:06

In a situation where Apache is sitting behind a reverse proxy (such as Squid), the cgi environment variable REMOTE_ADDR gets the address of the proxy rather tha

相关标签:
9条回答
  • 2020-12-29 10:29

    Currently apache module mod_remoteip is the recommended way to do this; rpaf hasn't been reliably maintained, and can cause problems.

    0 讨论(0)
  • 2020-12-29 10:34

    Yes, we can do this.

    Just add a auto_prepend_file in your PHP.ini like auto_prepend_file = "c:/prepend.php" and in this file add this:

    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    

    You need the MOD_REMOTEIP in apache width RemoteIPHeader X-Real-IP.

    Cheers,

    Guiremach

    0 讨论(0)
  • 2020-12-29 10:34

    Since Apache 2.4 there is mod_remoteip built-in module that does this.

    1. Enable mod_remoteip
      (e.g. a2enmod remoteip)

    2. Create a list of trusted IP ranges (the IPs from which you accept the remote IP header). You can put them in a file like conf/trusted-ranges.txt

    3. Add this line to the Apache config:

      RemoteIPTrustedProxyList conf/trusted-ranges.txt
      
    4. Change your log file formats to use %a instead of %h for logging the client IP.


    For Cloudflare you need to trust all their IP ranges and use a custom header CF-Connecting-IP:

    RemoteIPHeader CF-Connecting-IP
    

    You can get Cloudflare ranges like this:

    curl https://www.cloudflare.com/ips-v4 > trusted-ranges.txt
    curl https://www.cloudflare.com/ips-v6 >> trusted-ranges.txt
    
    0 讨论(0)
提交回复
热议问题