views:

147

answers:

2

Hey everybody.

I've been trying to solve this for hours now but came up with nothing.

Inside .htaccess, whenever somebody requests an image from a folder of my website, I'm trying to check if a file with the same name exists in another folder; if it does, return that file; if it doesn't, return the file originally requested.

It seems so easy but it simply doesn't work. The .htaccess code is as follows:

RewriteEngine On

RewriteCond /images/blog/watermark/$1 -f
RewriteRule ^(.*) /images/blog/watermark/$1

The "RewriteCond" always returns negative, so the image requested is always loaded as is. If I change it to, like,

RewriteCond %{REQUEST_FILENAME} -f

it always returns positive, so it gets the image from the folder I want - except when the image's not there, generating an error, which is exactly what I'm trying to prevent.

What am I doing wrong?

Thanks.

+1  A: 

You have the wrong syntax for RewriteCond. You probably want to do something more like this:

RewriteCond ^/images/blog/watermark/(.*) -f

In this case $1 doesn't actually exist, because RewriteCond takes a regular expression, not a replacement string. So, Apache is looking for /images/blog/watermark/$1 instead of any file inside of /images/blog/watermark/.

For reference: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteCond

Jeff Rupert
Thanks for your help. I've seen people using $1 in the RewriteCond clause before trying it, that's why it's there. I guess the way you wrote the clause it just checks if there are files in the folder, while what I want is to check if there is a file with the same name in that folder (hence the $1 reference that I was trying to use).Even so, changing the clause to this one always returns negative, as if there were no files in the folder :\
ultranol
A: 

I got it!

Apparently RewriteCond needs the whole directory structure to check file existence properly.

I added %{DOCUMENT_ROOT} before the path I previously had in my RewriteCond and it worked.

Also, after further reading the documentation, I noticed that the first group is $0 and not $1 when backreferencing from a RewriteRule.

So the final code is as follows:

RewriteEngine On 

RewriteCond %{DOCUMENT_ROOT}/images/blog/watermark/$0 -f 
RewriteRule ^(.*) /images/blog/watermark/$1 
ultranol