Doidgey Doidgey - 1 month ago 9
Apache Configuration Question

URL rewrite php query strings

I have two urls doing some queries which I'm struggling to rewrite in the manner I want.

First

/shop/index.php?category=catslug


which I want to be

/shop/category


Second

/shop/index.php?product=slug


to

/shop/category/product


I have this currently:

RewriteRule ^shop/([A-Za-z0-9-]+)/?$ shop/index.php?category=$1 [L]
RewriteRule ^shop/[A-Za-z-]+/([A-Za-z0-9-]+)/?$ shop/index.php?product=$1 [NC,L]


The problem is that one of the rules is ruining anything that starts with shop so that things like
shop/cart
doesn't work. I'm so confused. Is this possible?

Answer

Note that for shop/cart, the cart part matches the [A-Za-z0-9-]+ part of the first RewriteRule. So it is rewritten to shop/index.php?category=cart.

The way to avoid this, hoping that you have a relatively small number of fixed URLs, is to have a RewriteRule before your 2 rules like

RewriteRule ^shop/(cart|this|that|other|thing) - [L]
RewriteRule ^shop/([A-Za-z0-9-]+)/?$ shop/index.php?category=$1 [L]
RewriteRule ^shop/[A-Za-z-]+/([A-Za-z0-9-]+)/?$ shop/index.php?product=$1 [NC,L]

For requests matching one of the pipe-delimited strings (such as cart), - means don't change the request, and [L] means last (don't continue to the next rules).