Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

.htaccess - mod_rewrite with an unknown number of variables

I'm trying to use mod_rewrite to handle an unknown number of variables.

An example URL would be:

example.com/var1-var2-var3/title

I have this so far:

RewriteRule ^([^/.]+)-([^/]*)(.*)$ $3?version[]=$1&version[]=$2 [QSA,N]
RewriteRule ^([^/.]+)/?$ ?title=$1 [QSA,N]
RewriteRule ^/?$ /index.php [QSA,L]

This returns: Array ( [title] => title [version] => Array ( [0] => var1-var2 [1] => var3 ) )

I need it to return: Array ( [title] => title [version] => Array ( [0] => var1 [1] => var2 [2] => var3 ) )

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't think you can capture an arbitrary number of arguments in a single RewriteRule regex. Wouldn't it be easier to redirect to index.php?version=var-var2-var3 then in PHP do an explode() on $_POST['version']?

EDIT: You can do it for a bounded number of vars (9 is the maximum captured subgroups I believe) and then remove redundant empty entries. Messier then the simple explode() alternative in my opinion, but here you go:

# Convert up to 8 arguments.
RewriteRule ^/([^-]+)-(?:([^-]+)-)?(?:([^-]+)-)?(?:([^-]+)-)?(?:([^-]+)-)?(?:([^-]+)-)?(?:([^-]+)-)?(?:([^-]+)-)?/(.*)$ index.php?t=$9&v[]=$1&v[]=$2&v[]=$3&v[]=$4&v[]=$5&v[]=$6&v[]=$7&v[]=$8
# Strip empty ones.
RewriteRule [?&]v[]=$ "" [N]

You can also do a complicated loop by moving one var to the new format on each run of the rewriting engine and go on running it until you run out of vars, but I think that's more than a URL rewriting engine should be responsible for.

EDIT 2: Ok, here's the loop I mentioned:

RewriteEngine on
RewriteRule ^(.*)/([^/]+)$ $1&page=$2 [L]
RewriteRule ^([^-]+)-(.*)?$ $2&v[]=$1 [L]
RewriteRule ^(?!index.php)([^-]+)$ /index.php?v[]=$1 [L]

It transform a sample URL as follows:

var1-var2-var3/title                             <-- Original
var1-var2-var3&page=title
var2-var3&page=title&v[]=var1
var3&page=title&v[]=var1&v[]=var2
index.php?v[]=var3&page=title&v[]=var1&v[]=var2  <-- Final

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...