mod_rewrite to extensionless file results in 404

Viewed 28

On my server I have an image cache where all the image files are saved with the hash of their original location as their file name, without extension. I want to serve the images via mod_rewrite, with their original filename at the end of the URL.

For example, the physical location of an image file on the server is

/_img_cache/a/3/a3a37b602a1df1addfc8f2ff5a9824e1c9bd5273

I want to serve this image with the url

https://example.com/_img_cache/a/3/a3a37b602a1df1addfc8f2ff5a9824e1c9bd5273/OriginalFilename.jpg

So, I added this to my .htaccess file:

RewriteEngine On
RewriteRule ^_img_cache\/([a-z0-9])\/([a-z0-9])\/([a-z0-9]+)\/.+$ _img_cache/$1/$2/$3    [L]

It should just strip off the original filename part and serve me the file. I've tried this, but it gave me a 404 in return.

Unable to find my mistake, I made some slight modifications, added an extension to my test file, and changed the RewriteRule accordingly:

/_img_cache/a/3/a3a37b602a1df1addfc8f2ff5a9824e1c9bd5273.jpg
RewriteEngine On
RewriteRule ^_img_cache\/([a-z0-9])\/([a-z0-9])\/([a-z0-9]+)\/.+$ _img_cache/$1/$2/$3.jpg   [L]

If I request the same URL, I get my image served without problems. But it's not really the way that I wanted. I want it to work with the files as-is; extensionless. And that seems to be the only variable causing it to fail.

Why is Apache claiming the file without an extension, after rewrite, does not exist, while I've verified multiple times that it does. Is it a bug or a feature? Or am I missing something else? :)

1 Answers

Try this adjustment:

RewriteRule ^(_img_cache/([[:xdigit:]])/([[:xdigit:]])/\2\3[[:xdigit:]]{38})/.+ $1 [END,DPI]

Refer to the flags documentation, which warns that L can cause looping, which is rarely what people want. It should usually be combined it with DPI, and END is preferable if you don't need to check the rewritten path against any other rules.

Here's the explanation for the simplified regex.

Related