首页 > 解决方案 > htaccess 多个条件相同的 URL 重定向

问题描述

要求具有不同段(和/或查询参数)的多个 URL 重定向到单个着陆 URL 并终止

例如

/abc/def?hij=klm  => / (ROOT of domain)
/xzy?=(*)         => / (ROOT of domain  - anything )

我想要类似下面的东西(如果 QueryString 包含 ... 或包含 .... 等)

RewriteCond %{QUERY_STRING} ^abc/def(*)
RewriteCond %{QUERY_STRING} ^xyz?(*)
: (any other conditions here)
RewriteRule /$ http://www.example.com [301, L]

我知道可以根据.htaccess 将多个 url 重定向到其相应的新页面以每行为基础完成, 但我可能要输入数百个,所有这些都进入根域。因此尝试捕获多个条件并将它们全部重写到根域。

所以我要避免的是每个重定向都只有一行。如果上述情况不可行,那就是后备。任何帮助表示赞赏。

试图理解这一点:https ://httpd.apache.org/docs/2.4/mod/mod_rewrite.html 但似乎无法正确理解。

标签: .htaccessmod-rewriteurl-rewriting

解决方案


There are many issues with the attempt you posted. This does not really read like you actually considered the good examples given in the documentation you referenced...

Here is a version that should get you started, though you obviously need to adapt it to your specific requirements:

RewriteEngine on
RewriteCond %{QUERY_STRING} (?:^|&)abc=def(?:&|$) [OR]
RewriteCond %{QUERY_STRING} (?:^|&)xyz=([^&]*)(?:&|$) [OR]
RewriteCond %{QUERY_STRING} (?:^|&)uvw=([^&]*)(?:&|$) [OR]
RewriteRule ^/?$ http://www.example.com/ [R=301]

It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out...

This rule will work likewise in the http servers host configuration or inside a dynamic configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a dynamic configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).


推荐阅读