【问题标题】:Write to the Apache ErrorLog (404) when using RewriteRule/PHP使用 RewriteRule/PHP 时写入 Apache ErrorLog (404)
【发布时间】:2012-08-13 09:49:00
【问题描述】:

使用似乎相当标准的方法:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php [L]

所有请求都转到 index.php 文件来处理(除非 Apache 已经可以在磁盘上看到该文件)。

但是如果脚本确定请求的 URL 不存在 (404),那么如何将其记录在 Apache ErrorLog 中?

脚本返回 404 标头:

HTTP/1.1 404 Not Found

但是错误日志仍然是空的,而访问日志显示404:

192.168.2.2 - - [13/Aug/2012:10:39:35 +0100] "GET /404 HTTP/1.1" 404 32958

由于服务器托管多个网站,我希望它们都使用相同的机制来记录这些错误(而不是必须在 PHP 中写入第二个日志文件,或者试图让 PHP 进入 fopen/fread/fclose Apache 可能已经锁定的同一个文件)。

【问题讨论】:

    标签: php apache mod-rewrite url-rewriting


    【解决方案1】:

    您可以写入 stderr,因为 apache 会捕获它并将其附加到自己的错误日志中:

    $stderr = fopen('php://stderr', 'w'); 
    fwrite($stderr, 'My error'); 
    fclose($stderr);
    

    您还可以取消设置php.ini 中的error_log 指令,这将导致每个PHP 错误都附加到ErrorLog

    【讨论】:

    • 太好了,没有意识到如果你写信给 stderr,它会出现在 Apache 错误日志中......你知道它是否可以匹配 Apache 使用的 ErrorLogFormat 格式吗?
    • 有什么原因不能在 PHP 中编写格式吗?我的意思是,ErrorLogFormat 多久真正更改一次?
    • 可能永远不会,这就是我现在所做的......但我认为只定义一次该格式会很好(而不是 Apache 一个,每个网站一个最终使用这个)。
    • 嗯,可以稍微“破解”它。如果你创建一个文件,definitions.php 放置define ('APACHE_ERRORLOG_FORMAT', 'someFormatHere'),那么你可以使用 php.ini 指令auto_prepend_file = /path/to/definitions.php。带有常量的文件可以被所有使用 php.ini 作为定义的 PHP 安装使用。php 被添加到每个 PHP 文件中。
    • 谢谢@DavidS,这是一种解决方法......我想我会坚持你最初的建议,即在脚本中指定格式,并假设它至少与不过,Apache 使用了一个,只是因为我想减少黑客攻击的数量。
    【解决方案2】:

    还发现在<VirtualHost> 上写入“php://stderr”不会写入虚拟主机ErrorLog,而是转到主 Apache 错误日志。

    不过也有 PHP 函数 error_log()。

    error_log('File does not exist: ' . XXX, 4);
    

    4 表示它转到 Apache(SAPI 日志处理程序),而不是 php error_log 文件。

    http://php.net/error_log

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 2016-04-06
      • 2019-05-16
      • 2011-05-27
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      相关资源
      最近更新 更多