【问题标题】:Apache mod_rewrite rules not meetingApache mod_rewrite 规则不符合
【发布时间】:2017-02-12 00:22:10
【问题描述】:

我正在尝试转换此网址

http://www.example.com/test/products-list.php?category=cars&subcategory=coupe&color=blue

http://www.example.com/test/products/cars/coupe/blue

这些是我正在使用的规则:

RewriteRule products/(.*)/(.*)/(.*)/ /test/products-list.php?category=$1&subcategory=$2&color=$3
RewriteRule products/(.*)/(.*)/(.*) /test/products-list.php?category=$1&subcategory=$2&color=$3

它适用于某些 URL:

http://www.example.com/test/products/cars ----> not working
http://www.example.com/test/products/cars/ ----> not working
http://www.example.com/test/products/cars/coupe ----> not working
http://www.example.com/test/products/cars/coupe/ ----> working
http://www.example.com/test/products/cars/coupe/blue ----> working
http://www.example.com/test/products/cars/coupe/blue/ ----> working

我该如何解决这 3 种情况下它不起作用?另外,它不工作的原因是什么?

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    我认为您的表达是在 products 一词之后寻找 3 或 4 个“/”。

    您的三个捕获 (.*) 使用“0 或更多”重复运算符“*”,但您的三个 / 是必需的。

    我相信http://www.example.com/test/products/cars// 会测试为工作正常。

    现在...如何解决?

    我想您将需要为每个搜索案例进行三种不同的重写。

    1. 类别
    2. 类别和子类别
    3. 类别、子类别和颜色

    您将在下面看到,我已使用“+”“重复运算符”在 categorysubcategory 的捕获中强制至少有 1 个字符em>颜色

    '/?'表达式末尾的 '/' 是可选的。这会将您上面的两条规则合二为一。

    RewriteRule products/(.+)/? /test/products-list.php?category=$1
    RewriteRule products/(.+)/(.+)/? /test/products-list.php?category=$1&subcategory=$2
    RewriteRule products/(.+)/(.+)/(.+)/? /test/products-list.php?category=$1&subcategory=$2&color=$3
    

    读者注意,我已经很多年没有做过Apache mod_Rewrite了,但我认为这只是一个正则表达式匹配的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-13
      • 2012-05-09
      • 2023-03-18
      • 1970-01-01
      相关资源
      最近更新 更多