.htaccess url用查询重写挑战

时间:2016-05-22 14:04:49

标签: php apache .htaccess mod-rewrite

有一点挑战。我在添加另一个"过滤器"时遇到问题。到我目前的重写代码。我想添加另一个重写,捕获url末尾的查询字符串(如果提供)

实施例..

example.com/search/?sort=newest   -->   example.com/search.php?sort=newest
example.com/search/first?sort=newest   -->   example.com/search.php?a=first&sort=newest
example.com/search/first/second?sort=newest   -->   example.com/search.php?a=first&b=second&sort=newest
example.com/search/first/second/third?sort=newest   -->   example.com/search.php?a=first&b=second&c=third&sort=newest

这是我目前的代码。

# search without filters
RewriteRule    ^search?$    search/    [NC,L]

# search with one filter
RewriteRule    ^search/([A-Za-z0-9-+]+)?$    search.php?a=$1    [NC,L]

# search with two filters
RewriteRule    ^search/([A-Za-z0-9-]+)/([A-Za-z0-9-+]+)?$    search.php?a=$1&b=$2    [NC,L]

# search with three filters
RewriteRule    ^search/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-+]+)?$    search.php?a=$1&b=$2&c=$3    [NC,L]

1 个答案:

答案 0 :(得分:1)

要将现有查询字符串保留在RewriteRule中,您无需执行任何操作。

但是如果您在替换部分中自己添加查询字符串,则需要使用QSA标志附加上一个查询字符串

RewriteRule ^search/([A-Za-z0-9-+]+)?$ search.php?a=$1 [NC,L,QSA]