htaccess mod_rewrite check file/directory existence, else rewrite?

Posted by devians on Stack Overflow See other posts from Stack Overflow or by devians
Published on 2010-03-12T02:13:50Z Indexed on 2010/03/17 1:01 UTC
Read the original article Hit count: 507

I have a very heavy htaccess mod_rewrite file that runs my application. As we sometimes take over legacy websites, I sometimes need to support old urls to old files, where my application processes everything post htaccess.

My ultimate goal is to have a 'Demilitarized Zone' for old file structures, and use mod rewrite to check for existence there before pushing to the application.

This is pretty easy to do with files, by using:

RewriteCond %{IS_SUBREQ} true
RewriteRule .* - [L]

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [L]

RewriteCond Public/DMZ/$1 -F [OR]
RewriteRule ^(.*)$ Public/DMZ/$1 [QSA,L]

This allows pseudo support for relative urls by not hardcoding my base path (I cant assume I will ever be deployed in document root) anywhere and using subrequests to check for file existence. Works fine if you know the file name, ie http://domain.com/path/to/app/legacyfolder/index.html

However, my legacy urls are typically http://domain.com/path/to/app/legacyfolder/

Mod_Rewrite will allow me to check for this by using -d, but it needs the complete path to the directory, ie

 RewriteCond Public/DMZ/$1 -F [OR]
 RewriteCond /var/www/path/to/app/Public/DMZ/$1 -d
 RewriteRule ^(.*)$ Public/DMZ/$1 [QSA,L]

I want to avoid the hardcoded base path. I can see one possible solutions here, somehow determining my path and attaching it to a variable [E=name:var] and using it in the condition.

Another option is using -U, but the tricky part is stopping it from hijacking every other request when they should flow through, since -U is really easy to satisfy.

Any implementation that allows me to existence check a directory is more than welcome. I am not interested in using RewriteBase, as that requires my htaccess to have a hardcoded base path.

© Stack Overflow or respective owner

Related posts about htaccess

Related posts about apache