单个或多个文件夹的重写规则

rewrite rule for single or multiple folders

我的 htaccess 代码 URL 重写:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^compare/(.*)/?$ compare.php?page= [L,QSA]
RewriteRule ^compare/(.*)/(.*)?$ compare.php?page=&location= [L,QSA]

此规则适用于:

www.example.com/compare/car

但不适用于:

www.example.com/compare/car/india

我想修改适用于这些网址的重写规则:

www.example.com/compare/car
www.example.com/compare/car/india

可能吗?我怎样才能修改我的重写规则来实现这个?

您的代码有 2 个问题:

    第一条规则中的
  1. .* 过于贪婪,它匹配 / 所以第一条规则也匹配 /compare/car/india 以及 /compare/car
  2. 由于您的 URI 以 /compare 开头并且规则重写为 compare.php 您需要通过关闭 MultiViews.
  3. 来关闭内容协商
  4. 您的最后一条规则没有任何 RewriteCond,因为它仅适用于下一个直接 RewriteRule 指令。

您可以在站点根目录 .htaccess 中使用此代码:

Options -MultiViews
RewriteEngine On
RewriteBase /

# skip all files and directories from rewrite
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# one path element after compare
RewriteRule ^compare/([^/]+)/?$ compare.php?page= [L,QSA,NC]

# two path elements after compare
RewriteRule ^compare/([^/]+)/([^/]+)/?$ compare.php?page=&location= [L,QSA,NC]