Thursday, April 14, 2011

.htaccess redirect if file doesn't exist

So here's what I'm trying to do. I have a simple framework and I am using mod rewrite to rewrite the urls so that they point to the correct files. I have a process folder which sits inside the web folder (the web folder is where all the actual website files like images, css, etc are).

This works great but what I am trying to do now is to have a default.php file to process the forms. The file works great if I point the form to it but I want to be able to point the form to it's proper file and if the file is not there then it uses the default.php

The forms are create by a class and the action is set to go to process/{ID OF THE FORM}.php The idea is that anyone can create a form using the class and if they don't need to do anything special, the default.php file will process the form.

I realize I can just set the form class to always use the default.php and then on the default.php file I can check if the proper file exits. If it does, then use that file, if it doesn't then keep processing the form but I am still curious to know if something like this would work on mod rewrite:

RewriteRule ^process/([^/]*) /web/process/$1
RewriteCond %{DOCUMENT_ROOT}/web/process/$1 !-f
RewriteCond %{DOCUMENT_ROOT}/web/process/$1 !-d
RewriteRule ^process/([^/]*) /web/process/default.php [L]
From stackoverflow
  • You generally should have your RewriteCond calls before your RewriteRule. The Rule triggers if the Conds are met.

    Kyle Walsh : Are either situations working for you in test? It apperas that your logic for the default case is correct, but that the first Rule may be executed each time regardless.
  • I've answered a very similar question.

  • This rule alone should do it:

    RewriteCond %{DOCUMENT_ROOT}web/$0 !-f
    RewriteRule ^process/[^/]+$ web/process/default.php [L]
    

    If the requested path cannot be mapped to an existing file, it should be rewritten to the default file.

    David Zaslavsky : +1 This looks like it should work and it's neat and compact.

0 comments:

Post a Comment