5

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!

1
  • @faa The 1st example was simply to show the basis of my question (e.g. parameters taken from folders), while the 2nd was to show a page being served based on the number of parameters. By "number of folders accessed" I meant the number of parameters passed with the idea that 1 folder = 1 parameter, like so /path/to/folder -> 1 = path, 2 = to, 3 = folder. Commented Apr 21, 2013 at 23:01

1 Answer 1

8

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.