We have written about mod_rewrite before, but did you know that you can check if a file (or directory) exists before you attempt to redirect to it? Here’s how:
RewriteCond %{DOCUMENT_ROOT}/files/%{REQUEST_URI} -f
RewriteRule ^/([^/]*)$ /files/$1 [PT]
The RewriteCond checks for the existance of a file in the specified path, this is done with the special mod_rewrite rule -f. If you want to check if a file does not exist, you could use the following:
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI} !-f
Also, you can check for the existance of a directory with ‘-d’
The results of the above rule will allow the user, when they visit the URL
http://example.com/foo.html
to instead be served:
http://example.com/files/foo.html
so long as /files/foo.html exists. If it doesn’t, the usual behaviour will occur (such as other rewrites/redirects running, or causing a 404 error to be displayed).
Category: Useful tidbits
|
