3

Using Apache and mod_rewrite I can rewrite a complex request to a simple filename, eg:

RewriteRule ^shortcut/(.*)$ /long/way/around/$1

Can this work in reverse? I want a simple request to be rewritten to an unknown file, but I can identify which file should be served by a unique ID number prefixed to it's filename. I want Apache to "guess" using a regular expression which file to serve based on the ID.

For example:

GET /img/29281.jpg

Directory of /img/:
...
29280-filename-here.jpg
29281-other-filename-here.jpg  <-- Apache should serve this one
29282-more-files-here.jpg
...

So, a regular expression rewrite could perhaps be:

^(\d+)\.jpg$   -->   ^$1\-[a-zA-Z0-9-_]+.jpg$

How to integrate this into Apache (if it's possible)?

Many thanks for any suggestions.

P.S. Renaming all the filenames to the simple ID number isn't an option in this instance.

Ellipsis
  • 599
  • 1
  • 5
  • 8
  • Any experienced users out there: do you feel this question would be better placed on another site (stackoverflow comes to mind)? It's fairly programming-heavy and could probably exist over there? If so, what's the procedure to correctly cross-post? – Ellipsis Apr 29 '11 at 00:18
  • @Ellipsis - I agree that StackOverflow is the best destination for this question and I am moving it there now; in the future, please use the "flag" + "needs moderator attention" controls to expedite attention to your request. – danlefree May 03 '11 at 05:43
  • 1
    I think the best strategy would be to redirect `^(\d+)\.jpg$` to a script (e.g., PHP) and implement the "best guess" there instead. – jensgram May 03 '11 at 05:54

2 Answers2

1

I think one of the apache-way is to use mod-rewrite with the RewriteMap directive, and using the :prg mapping of the rewritemap.

This will load at apache start a simple program (may be a perl one as suggested in documentation, a PHP program may get more memleaks & performance problems, IMHO). This program will have to do the last part of the filename guess.

You can find some examples of such programs here (PHP), there (C), and here a Perl basic one.

I'm not enough perl-enabled in my brain to get the perl way of extracting real filename taking the extension and the int identifier but that should be easy and short (which is important for a PRG rewriteMap).

Community
  • 1
  • 1
regilero
  • 29,806
  • 6
  • 60
  • 99
  • Sounds like Apache doesn't have this built-in, so this looks like the most powerful approach; although Creadiff's 404 solution is a good work-around. – Ellipsis Oct 15 '11 at 02:26
0

You could use a PHP script as an ErrorDocument for the 404 page. This script would find the desired file, and send a redirection to the wanted file.

Mathieu Rodic
  • 6,637
  • 2
  • 43
  • 49