在 Apache 中修改 LogFormat

在 Apache 中修改 LogFormat

我需要修改 Apache 中的 LogFormat,以便添加X-Forwarded-For标头并记录客户端的真实 IP。我尝试在httpd配置文件文件,但随后我发现 LogFormat 有两个单独的部分。因此,我不确定它们是否重复,我是否应该删除其中任何一个,我不知道要编辑其中哪一个,还是应该编辑它们全部。我需要一些建议。

以下是第一部分:

<IfModule log_config_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    CustomLog "logs/access_log" common

    <IfModule logio_module>
        LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio

    </IfModule>

</IfModule>

第二部分:

<IfModule mod_log_config.c>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common
    LogFormat "%{Referer}i -> %U" referer
    LogFormat "%{User-agent}i" agent

    CustomLog logs/access_log common

</IfModule>

我不知道第一部分和第二部分有什么区别。我可以看到两部分中有两行重复。那么,我应该编辑哪一部分?删除一部分的重复行并保留另一部分是否安全?我可以将不重复的行合并到一个部分中吗?谢谢。

答案1

IfModule 指令仅在模块已加载时才采用配置。要检查已加载哪些模块,您可以使用

  • httpd -M -f path-to-config-file使用 Linux
  • httpd -t -D DUMP_MODULES使用 Windows

例子

[root@apachesrv bin]# httpd -M -f conf/httpd-vserver.conf
Loaded Modules:
 core_module (static)
 ...
 log_config_module (shared)
 ...
 proxy_http_module (shared)
 schema_module (shared)
Syntax OK

在这种情况下,您可以看到我正在使用 log_config_module,因此它将采用(就我而言)配置

<IfModule log_config_module>
  LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
  LogFormat "%h %l %u %t \"%r\" %>s %b" common

  CustomLog "logs/access_log" common

  <IfModule logio_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio    
  </IfModule>    
</IfModule>

为了获取所需的信息,您需要配置类似以下内容的日志:

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{X-Forwarded-For}i\"" combinedcustomized

然后将访问日志更改为:

CustomLog logs/access.log combinedcustomized

编辑:

在 apache 文档中,您可以找到可用于记录的参数列表http://httpd.apache.org/docs/2.4/mod/mod_log_config.html

答案2

根据Apache 文档两个部分是等效的:

Description:    Logging of the requests made to the server
Status: Base
Module Identifier:  log_config_module
Source File:    mod_log_config.c

删除(或注释掉)您不想使用的那个,否则如果由于某种原因您改变了它们的顺序(因此优先级),您以后会遇到各种各样的麻烦。

答案3

在我的 centos 7.4 上我只有

<IfModule log_config_module>

httpd.conf 中的指令,并且 log_config_module 通过 /etc/httpd/conf.modules.d/00-base.conf 配置文件加载

我只改变了这一行以使其工作。(但是你会因为客户端 ip 的新行而更改日志格式)

LogFormat "%h %{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

有一种更“优雅”的方法可以做到这一点(如果存在 x-forwarded-for 字段,则用客户端 ip 替换代理 ip)但我无法让它工作(只显示代理 ip)

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combied
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" proxy
SetEnvIf X-Forwarded-For "^.*\..*\..*\..*" forwarded
CustomLog "logs/access_log" combined env=!forwarded
CustomLog "logs/access_log" proxy env=forwarded

相关内容