3

I'm looking for a way to rewrite all my image requests from one folder into some.php file, while preserving the original image url (or partial path).

So,

example.com/folder/img/test.jpg

would be rewrited as something like

example.com/folder/some.php?img=img/test.jpg

(is this the best approach?)

I'm not familiarized enought witrh regular expressions, so I'll be very thankfull :)

note : I've tried some solutions before, none of them worked. ALso, I'm running Apache 2.0 under CentOS environment.

Charles
  • 50,943
  • 13
  • 104
  • 142
yoda
  • 10,834
  • 19
  • 64
  • 92
  • Adding the php file in the folder of the request image seems a bit strange, you most probably want the php file in the root folder. Otherwise, it means that you have some.php on each images folder, or another rewrite rule to process that. – PatomaS Oct 17 '12 at 01:38
  • It's not strange, it's a feature. – yoda Oct 17 '12 at 10:40

3 Answers3

4

Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteRule ^(folder)/(img/[^.]+\.jpg)$ $1/some.php?img=$2 [L,QSA,NC]

Make sure:

  • .htaccess is enabled
  • mod_rewrite is enabled
  • Your URL is http://example.com/folder/img/test.jpg
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Although your answer works as well as any other answers here so far, you gave me the hint that I needed. Mod_Rewrite wasn't working at all, because I was working on a vhost that didn't had any `` instructions, thus not allowing url override by default. – yoda Oct 17 '12 at 13:34
2

It sounds like you you want the filename of the image in the url to be included in the new php url, not the entire url. So something like:

RewriteRule ^folder/img/(.*[.]jpg)$ /folder/some.php?filename=$1
William Greenly
  • 3,914
  • 20
  • 18
  • Can you be a little more specific. What actually happens. – William Greenly Oct 17 '12 at 11:30
  • Nothing happens. I access `example.com/folder/img/test.jpg` and it just displays the image as is, when it should redirect to php and dump the `GET` request on the screen. – yoda Oct 17 '12 at 13:01
1

Considering what you mention in the comments and that the previous rules didn't work, I edited the message, this is what i have now.

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} ^/(.*)\.jpg [NC]
RewriteRule ^folder/img/([\w]*\.jpg)$ folder/some.php?img=img/$1[R=301,L]

If folder is al variable, you can change that for (\w*) and add the reference in the right side of the rule.

Hope this helps.

Bye

PatomaS
  • 1,603
  • 18
  • 25