chrisrth
chrisrth

Reputation: 1212

Rewrite URL containing directory path and parameters to parameter based URL using both path and query string

I use htaccess to rewrite this path:

/inventory/products/tools/

to this url with query string:

/inventory.php?cat=products&type=tools

using the following rule:

RewriteRule ^inventory/(.*)/(.*)/? /inventory.php?cat=$1&type=$2 [L,R=301]

When I add a query string to my url path

/inventory/products/tools/?sort=pricehigh

and use this rule

RewriteCond %{QUERY_STRING} ^(.*)$ [NC]
RewriteRule ^inventory/(.*)/(.*)/? /inventory.php?cat=$1&type=$2&%1 [L,R=301]

I am getting a redirect loop and the urlstring is rewritten over and over

I am trying to end up with the following destination url

/inventory.php?cat=products&type=tools&sort=pricehigh

In the example rule above I am using R=301 in order to visualize the url. In a production I would use [L] only

Upvotes: 1

Views: 1116

Answers (1)

C3roe
C3roe

Reputation: 96383

Without the trailing slash, the second (.*) also allows for matching zero characters - so due to the greediness of regular expressions, the first (.*) matches products/tools already.

The following should work:

RewriteRule ^inventory/([^/]+)/([^/]+)/?$ /inventory.php?cat=$1&type=$2 [QSA,L,R=302,NE]

([^/]+) demands one or more characters, out of the class of characters that contains everything but the /.

The NE/noescape flag seems necessary here for some reason, otherwise the resulting query string will contain ?cat=products%26type=..., with the & URL-encoded.

Upvotes: 2

Related Questions