.htaccess: Backreference in RewriteCond to check for file existence

.htaccessmod-rewriterewritecond

I'm trying to match URLs of this type:

http://www.example.com/image/12345

I'd then like to check whether this file exists:

http://www.example.com/files/image_12345.jpg

If it does, I'd like to rewrite the URL to point to that file.

If it doesn't I'd like to rewrite the URL to point to my image-generating script:

http://www.example.com/img_gen.php?id=12345

Here's what I've got so far:

RewriteCond %{REQUEST_FILENAME} ^/image/([0-9]+)$
RewriteCond %{DOCUMENT_ROOT}/files/images_%1.jpg !-f
RewriteRule ^image/([0-9]+)$ img_gen.php?id=$1 [L]

RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^image/([0-9]+)$ /files/images_$1.jpg [L]

But all I'm getting is a 404.

Best Answer

If you can't figure out what your Rewrite Rules are doing you should enable RewriteLog with some increased verbosity:

RewriteLogLevel 3
RewriteLog "/var/log/rewrite.log"

This should give you a pretty good starting position in further investigation of what's going on wrong.

Related Topic