使用路径和查询字符串将包含目录路径和参数的URL重写为基于参数的URL。

问题描述 投票:0回答:1

我用htaccess重写这个路径。

/inventory/products/tools/

改写成这个带有查询字符串的url。

/inventory.php?cat=products&type=tools

改写为这个url,并使用以下规则。

RewriteRule ^inventory/(.*)/(.*)/? /inventory.php?cat=$1&type=$2 [L,R=301]

当我在我的url路径中添加一个查询字符串时。

/inventory/products/tools/?sort=pricehigh

并以此为规则

RewriteCond %{QUERY_STRING} ^(.*)$ [NC]
RewriteRule ^inventory/(.*)/(.*)/? /inventory.php?cat=$1&type=$2&%1 [L,R=301]

我得到了一个重定向循环,urlstring被重写了一遍又一遍。

我试图用下面的目标网址来结束。

/inventory.php?cat=products&type=tools&sort=pricehigh

在上面的规则示例中,我使用R=301来可视化url。在生产中,我只使用[L]。

apache .htaccess mod-rewrite
1个回答
1
投票

如果没有尾部的斜杠,第二条 (.*) 也允许匹配零字符--所以由于正则表达式的贪婪,第一个 (.*) 匹配 products/tools 已经。

下面的方法应该可行。

RewriteRule ^inventory/([^/]+)/([^/]+)/?$ /inventory.php?cat=$1&type=$2 [QSA,L,R=302,NE]

([^/]+) 要求一个或多个字符,从包含所有字符的类中,除了 /.

NEnoescape 标记似乎是必要的,否则查询结果将包含 ?cat=products%26type=...,与 & URL编码的。

© www.soinside.com 2019 - 2024. All rights reserved.