使用 RewriteRule/PHP 时写入 Apache ErrorLog (404)


Write to the Apache ErrorLog (404) when using RewriteRule/PHP

使用似乎是相当标准的:

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 打开/复制/关闭 Apache 可能已经锁定的同一文件)。

你可以写信给stderr,因为apache会捕捉到这一点并将其附加到自己的错误日志中:

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

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

还发现写入<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