解决Apache获取客户端真实IP的问题

起因:

服务器端部署apache+php应用,使用$_server[‘remote_addr’]获取的ip为127.0.0.1。虽然说可以通过其他方案来获取正确的ip,但强迫症发作,觉得这是不可接受的。

解决方案:

作为反代服务器的NGINX配置:

确保server中包含以下内容:

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

作为后端服务器的Apache配置:

1、启用mod_remoteip模块

a2enmod remoteip

或(debian系统有效):

sudo ln -s /etc/apache2/mods-available/remoteip.load /etc/apache2/mods-enabled/remoteip.load

2、修改配置文件(以debian为例)

方案一:在使用Cloudflare后,客户端的真实ip会被放在HTTP_CF_CONNECTING_IP中,直接使用即可

在apache2.conf中或虚拟主机的配置文件中添加以下内容

<IfModule remoteip_module>
RemoteIPHeader CF-Connecting-IP
RemoteIPInternalProxy 127.0.0.1/24
</IfModule>

修改apache access log格式(在/etc/apache2/site-enable/*.conf中添加或修改)

LogFormat "%{CF-Connecting-IP}i %l %u %t "%r" %>s %O "%{Referer}i" "%{User-Agent}i"" proxied
CustomLog ${APACHE_LOG_DIR}/access-example.com.log proxied

方案二:手动剔除Cloudflare所有的ip

Cloudflare使用的ip可以在https://www.cloudflare.com/ips/查询

<IfModule remoteip_module>
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 127.0.0.1/24
#CloudFlare IP Ranges
RemoteIPInternalProxy 103.21.244.0/22
RemoteIPInternalProxy 103.22.200.0/22
RemoteIPInternalProxy 103.31.4.0/22
RemoteIPInternalProxy 104.16.0.0/12
RemoteIPInternalProxy 108.162.192.0/18
RemoteIPInternalProxy 131.0.72.0/22
RemoteIPInternalProxy 141.101.64.0/18
RemoteIPInternalProxy 162.158.0.0/15
RemoteIPInternalProxy 172.64.0.0/13
RemoteIPInternalProxy 173.245.48.0/20
RemoteIPInternalProxy 188.114.96.0/20
RemoteIPInternalProxy 190.93.240.0/20
RemoteIPInternalProxy 197.234.240.0/22
RemoteIPInternalProxy 198.41.128.0/17
</IfModule>

其他:若未使用cdn:

<IfModule remoteip_module>
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 127.0.0.1/24
</IfModule>

3、补充:若后端服务器为NGINX

在配置文件中添加:

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