jerrygarciuh
jerrygarciuh

Reputation: 22018

Getting x number of variables in mod_rewrite from "directories"

This rewrite rule works fine for domain.com/news but I would like be able to parse multiple levels into variables like domain.com/news/2012/party/zeke etc

I tried experimenting with the regex but failed badly.

RewriteEngine on
RewriteBase /
RewriteRule ^([^/\.]+)/?$ page.php?page=$1 [L]

Also tried solutions here: mod_rewrite with multiple variables

using mod_rewrite to simulate multiple sub-directories

// EDIT: It seems I can just add one rule per level BUT is it possibel to have one rule that does all levels?

RewriteRule ^([^/\.]+)/?$ /page.php?page=$1 [L]

RewriteRule ^([^/\.]+)/([^/\.]+)/?$ /page.php?page=$1&sub=$2 [L]

Upvotes: 0

Views: 374

Answers (1)

baynezy
baynezy

Reputation: 7066

You can have recursive rules however all of the parts of your rewrite are data. So how can it be converted to a query string as it does not know how to name the variables.

If you had /section/news/year/2012/user/zeke/ then you could use (NOT TESTED):-

RewriteRule ^section/\w+/([^/]+)/([^/]+)/(.*)$      news/$3?$1=$2 [NC,N,QSA]
RewriteRule ^section/(\w+)/?$                       page.php?page=$1 [NC,QSA,L]

This should end up rewriting to `page.php?page=news&year=2012&user=zeke

With what you are trying to do you are going to have to change your requirements and use a version of the above or pass them all down to a page in PHP and do the work in PHP.

Upvotes: 1

Related Questions