URL 重写 - .htaccess 规则:URL 末尾的斜杠会弄乱所有 URL



我的.htaccess中有以下规则

<IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule .* - [L]
    # single product page
    RewriteRule ^uleiuri/(.*)/(.*)/(.*)-([0-9]+)/?$ produs.php?id=$4 [L]
    # oils page by category and brand
    RewriteRule ^uleiuri/(.*)/(.*)/?$ uleiuri.php?cat=$1&brand=$2 [L]
    # oils page by category
    RewriteRule ^uleiuri/(.*)/?$ uleiuri.php?cat=$1 [L]
</IfModule>

它的作用:website.com/uleiuri显示所有产品,website.com/uleiuri/category-name显示某个类别的所有产品,website.com/uleiuri/category-name/brand-name,显示某个类别以及某个品牌的所有产品,最后website.com/uleiuri/category-name/brand-name/name-of-the-product-x是产品页面。

就像现在一样,它可以工作,但是如果我在其中任何一个的末尾添加一个/,规则就会失败,它会向我显示所有产品,例如website.com/uleiuri/category-name/brand-name/返回所有产品。

我希望问题清楚,并感谢您的帮助。

您应该避免与*匹配,而改用+。更重要的是,你的规则是"贪婪的",这就是为什么很多东西是匹配的。您应该将(.*)替换为仅将字符串与/字符和至少一个字符匹配的([^/]+)

当用户使用您的规则输入地址:website.com/uleiuri/category-name/brand-name/时,cat变量填充category-name/brand-namebrand是一个空字符串,这可能就是返回所有产品的原因。

您的规则应如下所示:

<IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule .* - [L]
    # single product page
    RewriteRule ^uleiuri/([^/]+)/([^/]+)/([^/]+)-([0-9]+)/?$ produs.php?id=$4 [L]
    # oils page by category and brand
    RewriteRule ^uleiuri/([^/]+)/([^/]+)/?$ uleiuri.php?cat=$1&brand=$2 [L]
    # oils page by category
    RewriteRule ^uleiuri/([^/]+)/?$ uleiuri.php?cat=$1 [L]
</IfModule>

最新更新