Apache RewriteRule不将变量拆分为查询字符串

时间:2016-09-16 22:33:29

标签: apache .htaccess mod-rewrite

<Directory /var/www/html/api/>
        RewriteEngine on
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^([^/]*)(.*)$ index.php?version=$1&method=$2&param1=$3&param2=$4&param3=$5
</Directory>

以下网址:http://myserver.com/api/v1/hello/there/stranger

array(5) { ["version"]=> string(2) "v1" ["method"]=> string(21) "/hello/there/stranger" ["param1"]=> string(0) "" ["param2"]=> string(0) "" ["param3"]=> string(0) "" }

版本字符串正确分割,但方法字符串似乎占用其余内容并将其放入一个字符串中,而不是将其拆分为param1,param2和param3,这是我的目标。

如何'重写'RewriteRule以便正确地将这些变量拆分成匹配的查询字符串?

1 个答案:

答案 0 :(得分:1)

它没有分裂,因为你的正则表达式没有将它分成多个组。

您的正则表达式在(.*)之后捕获v1/,它将在一个组中捕获/hello/there/stranger

您可以使用以下不同的规则:

# 2 parts
RewriteRule ^([^/]+)(/[^/]+)/?$ index.php?version=$1&method=$2 [L,QSA]

# 3 parts
RewriteRule ^([^/]+)(/[^/]+)(/[^/]+)/?$ index.php?version=$1&method=$2&param1=$3 [L,QSA]

# 4 parts
RewriteRule ^([^/]+)(/[^/]+)(/[^/]+)(/[^/]+)/?$ index.php?version=$1&method=$2&param1=$3&param2=$4 [L,QSA]

# 5 parts
RewriteRule ^([^/]+)(/[^/]+)(/[^/]+)(/[^/]+)(/[^/]+)/?$ index.php?version=$1&method=$2&param1=$3&param2=$4&param3=$54 [L,QSA]