如何用mod_rewrite将URL重写为含PHP数组参数的格式?
Solution for Dynamic URL Rewrite to Array Params
Got it, let's tackle this URL rewrite challenge. The core issue is splitting an unknown number of trailing path segments into a params[] array in your query string—mod_rewrite doesn't do this natively, but we can use a looping approach to build the array step by step.
Here's the complete .htaccess code you need:
RewriteEngine On RewriteBase / # Skip direct access to index.php to avoid infinite loops RewriteCond %{REQUEST_URI} !^/index\.php$ # Loop rule: Move the last path segment into a new params[] element RewriteRule ^(.*)/([^/]+)$ $1?params[]=$2 [QSA,N] # Final rewrite: Map controller/action to index.php, append all params[] RewriteRule ^([^/]+)/([^/]+)$ index.php?controller=$1&action=$2 [QSA,L]
How It Works
Let's walk through what happens with your example URL https://example.com/foo/bar/123/asd/qwerty:
- First loop iteration: The URL gets rewritten to
https://example.com/foo/bar/123/asd?params[]=qwerty(we strip the last segmentqwertyand add it as the firstparams[]element). TheNflag tells mod_rewrite to restart processing from the first rule. - Second loop iteration: Now the URL is
https://example.com/foo/bar/123/asd?params[]=qwerty—it gets rewritten tohttps://example.com/foo/bar/123?params[]=asd¶ms[]=qwerty. - Third loop iteration: The URL becomes
https://example.com/foo/bar/123?params[]=asd¶ms[]=qwerty, which gets rewritten tohttps://example.com/foo/bar?params[]=123¶ms[]=asd¶ms[]=qwerty. - Final rewrite: Now we're left with just
foo/barin the path. The second rule matches this, rewriting tohttps://example.com/index.php?controller=foo&action=bar¶ms[]=123¶ms[]=asd¶ms[]=qwerty.
Key Flags Explained
QSA: Stands for "Query String Append"—it ensures existing query parameters (like our growingparams[]array) are kept when adding new ones.N: Stands for "Next"—it restarts the rewrite process with the new URL, letting us loop through each trailing path segment.L: Stands for "Last"—it stops rewrite processing once we've mapped toindex.php.
Edge Cases Handled
- URLs with only
controller/action(no extra params): Directly maps toindex.php?controller=X&action=Ywith noparamsarray. - URLs with 1 extra param: Gets rewritten to
index.php?controller=X&action=Y¶ms[]=Z.
内容的提问来源于stack exchange,提问作者Dennis
相关产品推荐
相关产品推荐

