1

我的 .htaccess 文件中有这个

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

我想要做的是在这个配置中添加另一个 RewriteRule 以便像这样的旧 URL 将被重定向到站点的根目录

http://www.acme.com/category.php?id=6
http://www.acme.com/product.php?id=183&category= 

我知道“category.php”和“product.php”现在将是无效字符串。以“category.php”为例,我尝试将配置更改为

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^category.php(.*) / [L,R=301]
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

这将重定向如下

http://www.acme.com/category.php?id=112 -> http://www.acme.com/?id=112

我有两个问题

  1. 我不希望附加查询字符串。我没有指定 [QSA]
  2. 如果我直接输入根目录www.acme.com,除非我删除刚刚添加的行,否则页面不会显示。为什么我的新 RewriteRule 会影响不以“category.php”开头的 URL?

[编辑]

我也试过这个而不是上面的重定向,但我似乎仍然在应用这两个规则

RewriteRule ^category.php /holdingPage.php [L]
4

1 回答 1

1

您需要将 2 个条件绑定到发送所有内容的旧规则,index.php并且您需要在它们之上添加新规则:

RewriteEngine On
RewriteBase /

RewriteRule ^category.php /? [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

为了处理1.,我在规则目标的 / 末尾添加了一个“ ? ”。这使得查询字符串不会自动附加,除非你特别有QSA标志。至于2.,不确定为什么它对您不起作用,但它可能与应用于错误规则的 2 个条件有关。


编辑:

有关 2RewriteCond行的说明,请参阅这篇文章:https ://stackoverflow.com/a/11275339/851273

ARewriteCond本质上是一个条件,这个块:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

本质上是这样的(在伪代码中):

if(request_uri != maps_to_existing file) {
    if(request_uri != maps_to_existing_directory) {
        request_uri = request_uri.replace("([^?]*)", "index.php?_route_=$1", "[L,QSA]");
    }
}

事情是,一个RewriteCond或许多一个接一个,只适用于紧随其后的RewriteRule,所以如果不将 category.php 排除在前面,则伪代码 deo 等效项将是:

if(request_uri != maps_to_existing file) {
    if(request_uri != maps_to_existing_directory) {
        request_uri = request_uri.replace("^category.php", "/?", "[L,R=301]");
    }
}
request_uri = request_uri.replace("([^?]*)", "index.php?_route_=$1", "[L,QSA]");

这有点坏了,因为这两个if()条件被错误地应用了。特别是重写为“index.php”的那个需要条件以防止自身循环。

于 2012-07-16T17:10:39.423 回答