今天测试apache的rewrite功能,发现当使用apache虚拟主机,REQUEST_FILENAME(SCRIPT_FIENAME)值不正确。

想实现的功能:当请求文件不存在的时候,重定向uri到某一个地址。如下:

   RewriteEngine On

   RewriteCond %{REQUEST_FILENAME} !-f

   RewriteRule ^(.*)$/t.html [L]


上面这段配置加到httpd.conf的虚拟主机中,不管你请求的文件是否存在都会被重定向。原因是,在虚拟主机中,REQUEST_FILENAME的值相当于REQUEST_URI。 详见下面的英文文档说明。

REQUEST_FILENAME
The full local filesystem path to the file or script matching the request, if this has already been determined by the server at the timeREQUEST_FILENAME is referenced. Otherwise, such as when used in virtual host context, the same value as REQUEST_URI.

解决办法 :

1. 还是写在httpd.conf文件中, 加上%{DOCUMENT_ROOT}变量,让路径变全。

   RewriteEngine On

   RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f

   RewriteRule ^(.*)$/t.html [L]


2. 写在.htaccess文件中,该文件中%{REQUEST_FILENAME} 获取的值是正确的。

   RewriteEngine On

   RewriteCond %{REQUEST_FILENAME} !-f

   RewriteRule ^(.*)$/t.html [L]