amba88
amba88

Reputation: 789

Lighttpd URL rewrite with negative matching

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.

Upvotes: 0

Views: 1097

Answers (1)

latkin
latkin

Reputation: 16812

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

Upvotes: 1

Related Questions