R – Perform rewrite even if file at same URL exists (without getting error 500: infinite recursion)

.htaccessrewrite

I am trying to get rewriting working in an .htaccess file even when a file in the same location as the requested URL exists.

i.e. I want a rewrite of /about/index.html to happen even if there is a file at /about/index.html .

Currently I have:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^thehost.example.com$
RewriteCond %{REQUEST_URI} !^/dont-rewrite-when-at-this-url
RewriteRule ^(.*)(/|\.html|\.txt)$ /path/to/stubfile.html?/$1$2 [last,qsappend]

The problem is that if I request

http://thehost.example.com/about/index.html

and a file at /about/index.html exists (which is what I want, i.e. the rewrite should happen if the file DOES exist, though it would be fine for it also to happen if it didn't)

then I get error 500: infinite recursion.

(Adding a RewriteCond to exempt the stubfile itself being rewritten makes no difference.)

htaccess rewrite causes 500 error instead of 404 suggests that the absence of a -f RewriteCond prevents the recursion, but then that results in the behaviour I want not happening.

Is there a way to get the Rewrite to happen, i.e. ignore the fact that a file is there and just rewrite anyway even if there is a file of the same URL present?

Best Solution

Just exclude the destination you are redirecting to, in this case /path/to/stubfile.html:

RewriteCond %{HTTP_HOST} ^thehost.example.com$
RewriteCond %{REQUEST_URI} !^/dont-rewrite-when-at-this-url
RewriteCond %{REQUEST_URI} !=/path/to/stubfile.html
RewriteRule ^(.*)(/|\.html|\.txt)$ /path/to/stubfile.html?/$1$2 [last,qsappend]
Related Question