views:

461

answers:

1

Hi guys,

I'm trying to create an conditional Rewrite Rule using an .htaccess file and Apache.

Basically what I need is that the Apache would check if the requested file exists in a sub folder, case in which Apache would serve this existing file, or, if the file does not exist, Apache would load the index.php file.

The folder structure I'm using is:

- /gallery
  - /cache
  - index.php
  - .htaccess

also, the .htaccess I have now is

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.+) - [PT,L]
RewriteRule ^(.*)$ index.php/$1 [L]

however, this works only if the file I'm trying to look for is in the /gallery folder, however I need to look if the file exists in the /cache folder instead.

Does anyone know how to modify this rules in order to achieve that?

Thank you in advance,

titel

+1  A: 

Try these rules:

RewriteCond %{REQUEST_URI} ^/(([^/]+/)*)gallery/
RewriteCond %{DOCUMENT_ROOT}%1gallery/cache/$0 -f
RewriteRule ^.+ cache/$0 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.* index.php/$0 [L]

The first rule checks if the requested path is a path to an existing file in the cache directory. If so, it rewrites the request to that file.

Gumbo
First of all let me thank you for you trying to help out with this.However, the script you provided does not seem to work on my setup.When I'm trying to access something with the URL like "example.com/gallery/220-165-clouds.jpg" I don't either get the image even though the image exists in the /cache folder, and I don't get the index.php file either.What I get is an 404 Error :(Do you know what might be the reason for this?
titel
Just a little typo. It should work now.
Gumbo
It works fine for me. Try some debugging with mod_rewrite’s logging http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriteloglevel
Gumbo
Try to find out what value %{DOCUMENT_ROOT}%1gallery/cache/$0 is evaluated to. You can just append it to the URL: `RewriteCond %{REQUEST_URI} ^/(([^/]+/)*)gallery/ RewriteCond %{QUERY_STRING} ^$ RewriteRule ^.+ $0?%{DOCUMENT_ROOT}%1gallery/cache/$0 [L,R=301]`
Gumbo
YAY! it works! there was an slash (/) before the "gallery" on the second line.I've now got myself a very neat automatic image resize script with static file caching.Thanks a lot, you definitely deserve this correct answer.
titel
If your URL is fixed (so that it’s always `/gallery/…`), you can remove the first `RewriteCond` and the `%1` in the second `RewriteCond`. That was just for the case that there is more before `/gallery/…`.
Gumbo