Forum Moderators: phranque

Message Too Old, No Replies

interfering RewriteRules

         

luksus

4:35 pm on Nov 14, 2005 (gmt 0)

10+ Year Member



Hi,
have been looking for solution for this for couple hours.

I got two rules and they seem to interfere and always the first RewriteRule applies (wheather the URL is mydomain.com/12/show-all.html or mydomain.com/12/cars/category-search.html).

Do I need to use conditions or change url's structure to work around this. When I change the rules order it will work fine, but I would rather not do it.

example url: 12/show-all.html
RewriteRule (.*)/(.*).html /index.html?id=$1&title=$2 [L]

example url: 12/cars/category-search.html
RewriteRule (.*)/(.*)/(.*).html /index.html?id=$1&page=$2&title=$3 [L]

Many thanks.

jdMorgan

5:16 pm on Nov 14, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The problem is in the order of your rules, and the fact that a pattern of ".*" will match *anything*. You also have not anchored your patterns, and they may be far more ambiguous than necessary -- I can't tell from just two exmaples. As a result, anything that might match your second rule will be matched by your first rule, and so the second one won't ever be invoked.

The following code has been modified to be as specific and efficient as possible given your examples:


RewriteRule ^([^/]+)/([^/]+)/([^.]+)\.html$ /index.html?id=$1&page=$2&title=$3 [L]
RewriteRule ^([^/]+)/([^.]+)\.html$ /index.html?id=$1&title=$2 [L]

A general rule when using non-specific patterns is to always test the longer one first. This will often prevent problems.

If the URLs you want to rewrite always start with a numerical category, such as "12" in your example, then you can use the pattern "[0-9]+" to match only one or more numbers. If the category is always two digits, your could use "[0-9][0-9]" or "[0-9](2)" to match that. Try to use patterns that are very specific to each 'part' of the URL for best results and fewer "unexpected" rewrites.

For more information on mod_rewrite and regular expressions, see the documents cited in our forum charter [webmasterworld.com] and the tutorials in the Apache forum section of the WebmasterWorld library [webmasterworld.com].

Jim