regex – How to NOT match a word in mod_rewrite – Education Career Blog

Please help, I’m going crazy!

RewriteRule ^(a-z0-9_-+)?/?search/?$ search.php?id=$1&%{QUERY_STRING} NC,L

This is my current code. Sometimes people will visit, other times they will visit and I detect a user with an empty($_GET’id’) check.

However I am creating another search, which leads to products_search.php

I need my original RewriteRule to match any user EXCEPT the word ‘products’.

I have tried so many combinations.

RewriteRule ^(!products&a-z0-9_-+)?/?search/?$ search.php?id=$1&%{QUERY_STRING} NC,L

I’m not very good with regex/mod_rewrite but I something like the above should work? I just need an AND operator as clearly & doesn’t work, but I can’t find one!

Many thanks in advance.


You have two options: Either use a RewriteCond to restrict the already matched string:

RewriteCond $1 !=products
RewriteRule ^(a-z0-9_-+)?/?search/?$ search.php?id=$1&%{QUERY_STRING} NC,L

Or since Apache 2, you can also use a negated look-ahead assertion:

RewriteRule ^(?!products/)(a-z0-9_-+)?/?search/?$ search.php?id=$1&%{QUERY_STRING} NC,L

Besides that, you can also use the QSA flag instead of appending QUERY_STRING manually. And note that your current pattern will also allow something like /foobarsearch/, so it doesn’t have the separating /.


Not exactly “Not matching a word” – but you can add a Condition on the rewrite to say “If the URL doesn’t match this pattern”

RewriteCond %{REQUEST_URI} !^/products
RewriteRule ^(a-z0-9_-+)?/?search/?$ search.php?id=$1&%{QUERY_STRING} NC,L

Which is generally the most common way to do things like this – as conditions can also be chained together.

You can find more information about RewriteCond here :-


If mod_rewrite supports lookaheads, you can use

RewriteRule ^(?!products)(a-z0-9_-+)?/?search....

According to this question on newer versions do.

The part (?!products) tells the regex engine to look ahead and fail if it finds “products”.

Leave a Comment