I want to create .htaccess rule for situation like below:

Is something like this possible using .htaccess? I know that I can check if file exists with RewriteCond, but don't know if it is possible to redirect to the newest file.


There isn't a pure mod_rewrite solution for this. The closest thing may be using a RewriteMap to point to a script that always returns the newest file in /images/some. A simple script like this will always output the latest file in /images/some no matter the input:


while read in
    find /path/to/images/some/ -maxdepth 1 -type f -exec ls -t1 {} + | head -1 | sed -e 's|/path/to/images/some/||g'

And if you setup the map in the server or vhost config (maps can't be declared in htaccess):

RewriteMap latest prg:/path/to/script.sh

And you can invoke it like:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/?images/some/(.*)$ /images/some/${latest:$1} [L,R=301]

Of course, this isn't very efficient, and you're better off just writing a php routing script and direct everything to that instead of a map.

| improve this answer | |
  • Hi, can you explain why php will be faster than this? – Adrian Serafin Nov 14 '12 at 10:10
  • @AdrianSerafin I don't know which would be faster, but a php script could be more powerful, maybe rely on some type of cache, more configurable, etc. The prg map has the script running all the time, which is why you need to have an infinite loop, otherwise it will only work the first time because the script exits. – Jon Lin Nov 14 '12 at 10:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.