views:

42

answers:

3

I'm working on a legacy codebase, with three different folders of images. An image could be in any one of the three folders, in a pretty much random manner.

I initially attempted to check for file existence within PHP; however, images are being displayed in tons of places, and I'm hoping I can just achieve the same thing with an htaccess file. However, so far no luck.

Here's what I've got so far:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^Folder_1/(.*)$   Folder_2/$1   [L,NC]
RewriteRule ^Folder_2/(.*)$   Folder_3/$1   [L,NC]

What I'd like to happen is for any image request that doesn't exist, check the other two folders, in any order, for its existence. So, if someone requests Folder_3/image.png, it'll check Folder_1/image.png, then Folder_2/image.png

Any suggestions for how to write the htaccess file?

A: 

Use the [N] flag to start rewriting from the top again.

Ignacio Vazquez-Abrams
So like: [L,NC,N] ?
thekevinscott
A: 

In case you weren't able to get it to work based on Ignacio's suggestion, I'd suggest something like this, which, although a bit convoluted, seems to work:

RewriteEngine on

# If the request points to a real resource, just end here
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

# Check the other two directories
# First, figure out which directory we're currently in and capture the rest
RewriteCond $1|Folder_1|Folder_2|Folder_3 ^([^\|]+)\|(.*?)\|?\1\|?(.*)$
# Now break them up into two folders
RewriteCond %2|%3 ([^\|]+)\|([^\|]+)
# Check the first alternate folder to see if it exists there
RewriteCond %{DOCUMENT_ROOT}/%1/$2 -f [OR]
# If not, make the second option move to the first back reference
RewriteCond %2 ^(.*)$
# Check the second alternate folder to see if it exists there
# (or check the first option again if it succeeded..we could condition
#  this out in that case, but I don't know if it's worth adding)
RewriteCond %{DOCUMENT_ROOT}/%1/$2 -f
# If so rewrite to the correct alternate folder
RewriteRule ^([^/]+)/(.*)$ /%1/$2
Tim Stone
A: 

A RewriteCond directive does only belong to the very next RewriteRule directive. That means you would need to place these RewriteCond directives in front of each RewriteRule:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^Folder_1/(.+) Folder_2/$1 [L,NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^Folder_2/(.+) Folder_3/$1 [L,NC]

By the way: Your second condition %{REQUEST_FILENAME} !-d is probably useless as it only tests for an existing directory.

Gumbo