htaccess: rewriting unlimited subdirectories
I have a fairly complex content management system I've written in PHP, which has unlimited hierarchical categories.
Each category has a shortname (dynamically generated from the category title) which I using with mod_rewrite to produce clean URLs, for example
http://www.mysite.com/categories/january
The problem with this approach is that each category requires a unique shortname for it to work properly. This creates a problem when I have more than one category with the same name, with different categories, e.g. /categories/2011/january and /categories/2010/january.
The easiest way to overcome this is to append -1, -2 etc when a duplicate shortname is created, but I would much prefer to have the whole category hierarchy used in the URL and determine the right Ids based on this, e.g.
http://www.mysite.com/categories/2011/january vs http://www.mysite.com/categories/2010/january
My question is this: Is there a way that I can use mod_rewrite to parse any number of subcategories, and return these to my php page, perhaps as an array of values?
It would need to work regardless o开发者_高级运维f the number of subcategories, so it could process e.g.
http://www.mysite.com/categories/products/sheds/reports/2011/january
with the same code, and give my php page an array of those categories in the order they are shown in the URL?
My code would then need to work backwards from the last category to figure out which category is required based upon it's parents.
Is this something that would be feasible (and indeed recommended), and could anyone give me a hand with producing the correct regular expression for the rewrite command, given my pretty hopeless grasp of regex?
Many thanks in advance Nick
I don't think there is any easy way to let mod_rewrite split the data for you. Of course, you could build a RewriteRule
that matches up to 9 virtual paths, but I don't think that this would be helpful. Instead I would suggest to define a rule like this
RewriteRule ^categories/(.*)$ category-handler.php?cat=$1
and then do the splitting (and re-ordering) in the PHP file, something like this
$cat = $_GET['cat'];
$splittedCat = array_reverse(preg_split('/\//', $cat));
精彩评论