.htaccess RewriteRule only when a string doesn't exist

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
mfmickle
Forum Newbie
Posts: 2
Joined: Thu Mar 19, 2009 2:21 pm

.htaccess RewriteRule only when a string doesn't exist

Post by mfmickle »

I am new to regular expressions, so hopefully this is not a stupid question. I am trying to use a .htaccess file with a RewriteRule to identify only file names and/or paths that don't contain the string "thumb_". Right now I have an expression that can find "thumb_" in the provided string, but I need just the opposite. I need to know if string doesn't contain "thumb_". Below is the complete contents of my .htaccess file and I can't figure out how to reverse it. Any thoughts?

RewriteEngine on
RewriteRule ^(.*thumb_.*\.[jJ].*)$ watermark.php?i=$1

I want these to be returned: "img.jpg" and "gallery/img.jpg"
And I don't want these: "thumb_img.jpg" and "gallery/thumb_img.jpg"
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: .htaccess RewriteRule only when a string doesn't exist

Post by prometheuzz »

I know nothing about Apache's rewrite mod, but I do know a bit regex. The following regex will match any string NOT containing "thumb_":

Code: Select all

^(?:(?!thumb_).)*$
mfmickle
Forum Newbie
Posts: 2
Joined: Thu Mar 19, 2009 2:21 pm

Re: .htaccess RewriteRule only when a string doesn't exist

Post by mfmickle »

prometheuzz wrote:I know nothing about Apache's rewrite mod, but I do know a bit regex. The following regex will match any string NOT containing "thumb_":

Code: Select all

^(?:(?!thumb_).)*$
That worked...sort of. It is identifying the strings that contain "thumb_", but it's not looking for only images as my original post implied. Using your lead and further testing, I believe I have stumbled onto the solution.

Code: Select all

RewriteRule ^((?:(?!thumb_).)*\.(jpg|png).*)$ watermark.php?i=$1
Thank you so much! I pulled my hair out for two days on this and you basically solved it in six minutes.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: .htaccess RewriteRule only when a string doesn't exist

Post by prometheuzz »

mfmickle wrote:...

Thank you so much! I pulled my hair out for two days on this and you basically solved it in six minutes.
You're welcome.
Post Reply