本文为您介绍后端服务器如何获取访问 ALB 的客户端源 IP 地址。
X-Forwarded-For: 来访者真实IP, 代理服务器1-IP, 代理服务器2-IP, ...
本文以 CentOS 7.6 为例,您也可以按需替换为 CentOS 7.9、veLinux 1.0(CentOS兼容版)等CentOS 7系镜像。
请您根据后端服务器配置的 Web应用服务器类型选择适当的的配置步骤。本文为您介绍以下两种Web服务器:
参考登录Linux实例登录目标后端服务器。
依次执行以下命令,安装http_realip_module。yum -y install gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel
wget https://nginx.org/download/nginx-1.17.0.tar.gz
tar zxvf nginx-1.17.0.tar.gz
cd nginx-1.17.0
./configure --prefix=/path/server/nginx --with-http_stub_status_module --without-http-cache --with-http_ssl_module --with-http_realip_module
make
make install
执行以下命令,打开nginx.conf文件。vi /path/server/nginx/conf/nginx.conf
按i
进入编辑模式,在以下 server 配置信息后添加新的配置字段和信息。
server { listen 80; server_name localhost;
需要添加的配置字段和信息:
set_real_ip_from 100.64.0.0/10; real_ip_header X-Forwarded-For;
说明
按ESC退出编辑模式。
输入:wq保存并退出文件。
执行以下命令,启动 Nginx。/path/server/nginx/sbin/nginx
执行以下命令,查看 Nginx 的访问日志,您可以获取真实的客户端 IP。cat /path/server/nginx/logs/access.log
参考登录Linux实例登录目标后端服务器。
执行以下命令,查看Apache版本。httpd -v
回显如下,表示Apache版本为2.4.6。
Server version: Apache/2.4.6 (CentOS) Server built: Mar 24 2022 14:57:57
执行以下命令,打开 httpd.conf 文件。vi /etc/httpd/conf/httpd.conf
按i
进入编辑模式,修改日志格式并在文件末尾添加相关配置信息。
LogFormat "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined //在原内容中添加配置%{X-Forwarded-For}i CustomLog "logs/access_log" common //去掉此行配置前的注释符#:
LoadModule remoteip_module modules/mod_remoteip.so RemoteIPHeader X-Forwarded-For RemoteIPInternalProxy 100.64.0.0/10
说明
按ESC退出编辑模式。
输入:wq保存并退出文件。
执行以下命令,重启 Apache。systemctl restart httpd
执行以下命令,查看 Apache 的访问日志,您可以获取真实的客户端 IP。cat /etc/httpd/logs/access_log