How to NOT match a word in mod_rewrite
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 mysite.com/search, other times they will visit mysite.com/bo开发者_开发技巧ris/search and I detect a user with an empty($_GET['id']) check.
However I am creating another search, mysite.com/products/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 :- http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritecond
If mod_rewrite supports lookaheads, you can use
RewriteRule ^(?!products)([a-z0-9_-]+)?/?search....
According to this question on serverfault.com newer versions do.
The part (?!products)
tells the regex engine to look ahead and fail if it finds "products".
精彩评论