htAccess 重写规则冲突


htaccess rewrite rules conflict

www.example.com/category/sub_category/Having.htaccess文件中的rewririte规则问题。

我当前的 .htaccess 文件如下所示。

RewriteRule ^([0-9a-zA-Z_-]+)/([0-9]+)$ products.php?cat=$1&id=$2 [NC,L]
RewriteRule ^([^/]*)/([0-9a-zA-Z_-]+)/([0-9]+)$ product_categories.php?cat=$2&id=$3 [NC,L]
RewriteRule ^(.*)/(.*)/([0-9a-zA-Z_-]+)/([0-9]+)$ product_details.php?cat=$3&id=$4 [NC,L]
RewriteRule ^([0-9]+)$  gallery.php?id=$1 [NC,L]

我正在尝试创建如下所示的网址。

www.example.com/product_name/1
www.example.com/category/sub_category/21
www.example.com/category/sub_category/product_name/233
www.example.com/gallery/872

www.example.com/gallery/872 重定向到 www.example.com/category/sub_category/872 而不是图库.php?id=872

编辑:将网址从 www.example.com/gallery/872 更正为 www.example.com/category/sub_category/872。

您的问题是第一个规则匹配,最后一个规则永远无法应用......

RewriteEngine on
RewriteRule ^gallery/([0-9]+)/?$  gallery.php?id=$1 [NC,L]
RewriteRule ^([0-9a-zA-Z_-]+)/([0-9]+)$ products.php?cat=$1&id=$2 [NC,L]
RewriteRule ^([^/]*)/([0-9a-zA-Z_-]+)/([0-9]+)$ product_categories.php?cat=$2&id=$3 [NC,L]
RewriteRule ^(.*)/(.*)/([0-9a-zA-Z_-]+)/([0-9]+)$ product_details.php?cat=$3&id=$4 [NC,L]

经验法则:首先是特定的例外,然后是更一般的规则。

如果您在正则表达式模式中同时指定了小写和大写字母,则 NC 标志没有意义。它是非此即彼,不是和。

(注:我在他的回答中也附上了更正@anubhava)

您的最后一个规则将需要正则表达式修改,因为您匹配的是/gallery/872并且您的模式仅匹配 1 个或多个数字。

RewriteRule ^gallery/([0-9]+)/?$ gallery.php?id=$1 [NC,L,QSA]
RewriteRule ^([0-9a-zA-Z_-]+)/([0-9]+)$ products.php?cat=$1&id=$2 [QSA,L]
RewriteRule ^([^/]*)/([0-9a-zA-Z_-]+)/([0-9]+)$ product_categories.php?cat=$2&id=$3 [QSA,L]
RewriteRule ^(.*)/(.*)/([0-9a-zA-Z_-]+)/([0-9]+)$ product_details.php?cat=$3&id=$4 [QSA,L]

您还需要像我上面显示的那样记录您的规则。