0

I'm trying to rewrite urls that have an image in them but not 'php', for example:

I want to match this:

http://domain.com/trees.jpg

and rewrite it to this:

http://domain.com/viewimg.php?image=trees.jpg

But not match this:

http://domain.com/index.php?image=trees.jpg

because it has 'php' in it, so it shouldn't do any rewriting at all to that url.

I'm no good with regex but I've been trying a number of variations and none have worked. Here's an example of one variation I've tried:

url.rewrite-once = (
"(?!php\b)\b\w+\.(jpg|jpeg|png|gif)$" => "/viewimg.php?image=$1.$2"
)

Any help would be greatly appreciated, thanks.

amba88
  • 759
  • 3
  • 9
  • 27

1 Answers1

1

This should get you started. It will fail matches where there is the string \.php anywhere behind \w+\.(jpg|jpeg|png|gif)

Pattern: (?<!.*\.php.*)\b(\w+\.(jpg|jpeg|png|gif))$

Replace: viewing.php?image=$1

Tested:

http://domain.com/trees.jpg  --->  http://domain.com/viewing.php?image=trees.jpg
http://domain.com/index.php/trees.jpg  ---> http://domain.com/index.php/trees.jpg
http://domain.com/index.php/image=trees.jpg  ---> http://domain.com/index.php/image=trees.jpg

Edit:

Above uses non-constant-length lookbehind, which is apparently not supported on many platforms. Without this I don't know if you can codify "match XYZ when ABC is nowhere in the string behind it" in pure regex. Maybe someone with more regex-fu than me knows a way.

As a somewhat less general solution, this will check only if the fixed string .php?image= does not come right before the image name:

Pattern: (?<!\.php\?image=)\b(\w+\.(jpg|jpeg|png|gif))$

Replace: viewing.php?image=$1

latkin
  • 16,402
  • 1
  • 47
  • 62
  • Thanks for your answer but it doesn't seem to work for me. It doesn't rewrite http://domain.com/trees.jpg, I just get a 404. – amba88 Aug 21 '12 at 18:49
  • I tested it in .NET regex, maybe your env does not have the same feature set. Are you saying the match fails completely against `domain.com/trees.jpg` ? – latkin Aug 21 '12 at 19:35
  • Yes, I also tested it at http://gskinner.com/RegExr/ and it doesn't match any part of domain.com/trees.jpg. – amba88 Aug 21 '12 at 19:40
  • I see. I am using a variable-sized lookbehind, which is apparently only supported in .NET and JGsoft. http://www.regular-expressions.info/lookaround.html Let me see if I can change it. – latkin Aug 21 '12 at 19:50
  • Thank you so much for your help, that works great. However the 'image' string before '=' isn't always the same so I changed it to this and it works like a charm: (?<!=)\b(\w+\.(jpg|jpeg|png|gif))$ Thanks again for your help! – amba88 Aug 21 '12 at 20:39