With a little side of applesauce...

Monday, January 29, 2007

Apache mod_rewrite - Rewrite if file or directory does not exist

If you would like to rewrite a URL if the file or directory does not exist, and then append the %{REQUEST_FILENAME}, (the path after the Fully Qualified Domain Name), you would use:

# If the REQUEST_FILENAME does not exist as a file or directory
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-d
RewriteRule ^/(.*)$ http://www.example.com/main.php/$1 [L]

The first line:

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

tells Apache to check and see if the requested file exists, (ie index.php), by concatenating the %{DOCUMENT_ROOT}, (ie /var/www), and the %{REQUEST_FILENAME}, (ie /subweb/testing.htm).

Then testing to see if the requested directory exists:

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

Then, finally, rewriting everything under the root:

RewriteRule ^/(.*)$ http://www.example.com/main.php/$1 [L]

Examples:

With a FQDN of:

http://www.example.com

and a directory structure of:

./emacs
./emacs/semantic.cache
./emacs/.htaccess
./emacs/power-macros.el

http://www.example.com/emacs/power-macros.el

- > doesn’t rewrite

http://www.example.com/emacs

- > doesn’t rewrite

http://www.example.com/test #rewrites to

- > http://www.example.com/main.php/test

http://www.example.com/test/clock.htm #rewrites to

- > http://www.example.com/main.php/test/clock.htm

No comments: