I've setup a .htaccess
to redirect requests against the containing directory /htdocs/foo
to the file bar.php
.
1st of all: I know how to achieve this in general, but for reasons out of my control the .htaccess
also wants to check if the URL resolves to a regular file and redirects if not.
Doesn't sound too complicated, but I can't work this out. :[
This is my .htaccess
:
RewriteRule ^$ http://www.example.com/foo/bar.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* doh.php
These rules don't redirect www.example.com/foo
to bar.php
but doh.php
instead.
I checked the error.log
and for some reason the Rewrite Condition is matched although the file bar.php
is present.
RewriteCond: input='http://www.example.com/foo/bar.php' pattern='!-f' => matched
Apparently Apache doesn't consider bar.php
as regular file if a rewritten URL points to it. www.example.com/foo/bar.php
works as expected.
Any ideas why?
Edit #1:
For clarification, this is the file structure:
/ (File system root)
|
+ htdocs (Document root)
|
+ foo
|
+ .htaccess
+ bar.php
+ doh.php
Edit #2:
I'm running Apache 2.4.
Solution:
The RewriteCond
expects REQUEST_FILENAME
to contain a local path. Due the missing L
flag the RewriteRule
sets REQUEST_FILENAME
to a URL which obviously is not a local path, so the test for !-f
matches.
Ultimately, attaching the L
flag to the RewriteRule
produces the desired behavior:
RewriteRule ^$ http://www.example.com/foo/bar.php [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* doh.php
After the URL is rewritten to http://www.example.com/foo/bar.php
a new process loop is initiated, remapping the rewritten URL to the local path /htdocs/foo/bar.php
which doesn't match the RewriteCond
's !-f
test. And /htdocs/foo/bar.php
is passed through. :)