You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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:

  1. First loop iteration: The URL gets rewritten to https://example.com/foo/bar/123/asd?params[]=qwerty (we strip the last segment qwerty and add it as the first params[] element). The N flag tells mod_rewrite to restart processing from the first rule.
  2. Second loop iteration: Now the URL is https://example.com/foo/bar/123/asd?params[]=qwerty—it gets rewritten to https://example.com/foo/bar/123?params[]=asd&params[]=qwerty.
  3. Third loop iteration: The URL becomes https://example.com/foo/bar/123?params[]=asd&params[]=qwerty, which gets rewritten to https://example.com/foo/bar?params[]=123&params[]=asd&params[]=qwerty.
  4. Final rewrite: Now we're left with just foo/bar in the path. The second rule matches this, rewriting to https://example.com/index.php?controller=foo&action=bar&params[]=123&params[]=asd&params[]=qwerty.

Key Flags Explained

  • QSA: Stands for "Query String Append"—it ensures existing query parameters (like our growing params[] 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 to index.php.

Edge Cases Handled

  • URLs with only controller/action (no extra params): Directly maps to index.php?controller=X&action=Y with no params array.
  • URLs with 1 extra param: Gets rewritten to index.php?controller=X&action=Y&params[]=Z.

内容的提问来源于stack exchange,提问作者Dennis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:32:16