.htaccess 将带有查询参数的特定不存在的文件重定向到新的 url

.htaccess redirect specific non existing files with query parameters to a new url

我有一个自己的域,其中 url 具有 url 结构

https://www.olddomain.com/filename.php?cat=12
https://www.olddomain.com/filename.php?cat=12&id=1212122
https://www.olddomain.com/filename.php?cat=15
https://www.olddomain.com/filename.php?cat=15&id=121423

其中有一个或两个查询参数。现在我希望它重定向到一个新域,但具有不同的 url 结构,如下所示。

https://www.olddomain.com/filename.php?cat=12 -> https://www.newdomain.com/newurl_1/
https://www.olddomain.com/filename.php?cat=12&id=1212122 -> https://www.newdomain.com/newurl_1/
https://www.olddomain.com/filename.php?cat=15 -> https://www.newdomain.com/newurl_2/
https://www.olddomain.com/filename.php?cat=15&id=121423 -> https://www.newdomain.com/newurl_2/

它应该根据 "cat" 查询参数重定向到特定的 url。在 "cat" is/are 之后的 "id" 或任何其他查询 parameter/s 无关紧要。

这是我到目前为止所做的

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_URI} ^/filename.php [NC]
  RewriteCond %{QUERY_STRING} ^cat=12(.*) [NC]
  RewriteRule . /newurl_1/ [L,NC,R=301]
</IfModule>

上面的代码工作正常,除了它在新的 url 的末尾添加查询参数,就像这样

https://www.newdomain.com/newurl_1/?cat=12
https://www.newdomain.com/newurl_1/?cat=12&id=1212122
  1. 是否可以从新的 url 中删除额外的查询参数?
  2. 如何为多个不同的 "cat" 查询参数扩展我的 .htaccess?

For 1 Yes, you need to add a ? at the end of your rule:

RewriteRule . /newurl_1/? [L,NC,R=301]

因为查询字符串是自动附加的,但是带有 ?,除非您使用 QSA 标志,否则它不会被附加。

至于 2.,您需要为每个 cat 参数编写一个规则。您可以这样做,也可以考虑使用 RewriteMap(这在 htaccess 文件中不起作用)。如果您要枚举所有这些,您可能需要调整其中一个条件,使其看起来像这样:

RewriteCond %{QUERY_STRING} ^cat=12($|&) [NC]

所以它匹配 12 而不是 1234