要求
nginx代理后端apache服务器,并要求apache日志记录真实客户端IP地址
配置文件
root@AppSrv:~# sed -n "212,218p" /etc/apache2/apache2.conf
LogFormat "%{X-Forwarded-For}i:%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
#LogFormat "\"%{X-Forwarded-For}i\":%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
这时apache的日志格式配置,其中常用变量:
%h:客户端的IP地址
%t:访问时间
%r:请求的第一行(例如GET /index.html HTTP/1.1)
%s:服务器返回的HTTP状态码
%b:响应的字节数
%{Referer}i:客户端的Referer头
%{User-Agent}i:客户端的User-Agent头
%{Host}i:客户端请求的主机名(包含端口号)
%{Cookie}i:客户端的Cookie头
%{Content-Type}o:服务器返回的Content-Type头
X-Forwarded-For字段通常由反向代理或负载均衡器添加,以表示请求的原始客户端IP地址。
Apache在记录日志时会按照上述格式记录到日志中,后面的vhost_combined
、combined
、referrer
、agent
是这个格式的自定义名称,可以在site中调用:
${APACHE_LOG_DIR}为apache存储日志的路径,默认为/var/log/apache2/
命令格式为:
CustomLog 路径 LogFormat的自定义名称,表示此记录此日志的格式
Nginx代理日志管理
Nginx在代理时,可以在请求头上设置变量,服务器根据相关配置可以接收此变量。
server {
listen 80;
server_name ww.qwe.com;
location / {
proxy pass http://www1.qwe.com;
proxy_set_header qwe $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
}
}
在请求头中添加X-Forwarded-For字段,值为变量`$remote_addr`,常用变量如下:
$http_user_agent:客户端的User-Agent头
$http_referer:客户端的Referer头
$http_cookie:客户端的Cookie头
$host:客户端请求的主机名(不包含端口号)
$request_method:客户端的HTTP请求方法(例如GET或POST)
$request_uri:客户端的请求URI
$server_protocol:服务器的协议版本(例如HTTP/1.1)
$remote_addr:客户端的IP地址
$proxy_add_x_forwarded_for:所有上游代理服务器的IP地址和客户端的IP地址