Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache mod_rewrite path name as query parameters?

I want to use Apache's mod_rewrite in order to be able to take each folder of a path as a particular query parameter, for example consider the following:

Basic example

Url requested: http://domain.com/shoes/prada/image-1/

Page served: http://domain.com/?cid=shoes&bid=prada&pid=image-1

In this scenario, there are 3 sub-folders requested (/shoes/, /prada/ then image-1), so the first sub-folder is passed in the actual page served as cid, the second as bid and the third as pid.

Full example

However, I would also like it to serve a particular page depending on the number of sub-folders requested, e.g.

Url requested: http://domain.com/shoes/prada/

Page served: http://domain.com/shop.php?cid=shoes&bid=prada

So far all I've managed to find is regex based matching for mod_rewrite but my path's will vary a lot, which is why I would like to have conditions based on the number of folders accessed (please note, I'm not that good with regex - I reckon a wildcard character would help with this, but I wouldn't be sure where to start).

Any help on this would be greatly appreciated! This is pretty long winded, so if you need any more info for clarifying, please let me know!

like image 205
Kemebear Avatar asked Apr 21 '13 21:04

Kemebear


1 Answers

With a little bit of work I was able to tweak some regex and get a working rule set for what I wanted:

RewriteEngine on
RewriteRule ^(.*)/(.*)/(.*)/(.)?$ product.php?tid=$1&sid=$2&eid=$3 [L]
RewriteRule ^(.*)/(.*)/(.)?$ brand.php?tid=$1&sid=$2 [L]
RewriteRule ^(.*)/(.)?$ shop.php?tid=$1 [L]

This is a bit different to the example, however it's what I intended for in the first place.

This allows for the rewriting of url's up to four folders deep, with the "name" of each folder being given as a parameter, and each additional level of depth rewriting the url to a separate resource for example:

http://x.com/shoes/prada/2011-high-heels/ -> http://x.com/product.php?tid=shoes&sid=prada&eid=2011-high-heels

Tested on http://martinmelin.se/rewrite-rule-tester/

like image 90
Kemebear Avatar answered Sep 21 '22 23:09

Kemebear