除非规则匹配,否则需要重写

除非规则匹配,否则需要重写

我需要重写到另一个主机,除非 URL 以 /store 或 /utils 开头

我尝试查看 apache 文档,但我不知道该怎么做

答案1

好的,假设您想要重定向到主机 otherhost.example.com,这应该可以在 Apache 下解决问题。

RewriteCond %{REQUEST_URI}    !^/(store|utils)/.*
RewriteRule (.*)    http://otherhost.example.com$1 [R=301,L]

条件部分表示“如果请求 URI 不以 /store/ 或 /utils/ 开头,则应用重写。然后,重写规则将生成 301 重定向,并将捕获的 URI 附加到请求中。

答案2

正如 ickymettle 简洁地回答的那样,! 标志表示如果规则的条件不满足,则应将输入视为匹配。因此,分解语法:

! = 'Not' prefix
^ = start of string
/ = The first forward slash tells the rule to match only if the input string
    begins with a /
| = the pipe symbol denotes 'or' inside the bracketed group section
    (as in 'store or utils')
    The second forward slash denotes that the string ends with a forward slash
. = any single character
* = zero or more of the preceding character (so .* = 0 or more of any character, effectively passing on the rest of the URI

AddedBytes.com mod_rewrite 备忘单非常方便,我把它贴在了我座位旁边的墙上(因为我几乎每天都会深入研究 htaccess,并拼命尝试自学 mod_rewrite 魔法!)PerishablePress 上还有一篇非常详细的文章,其中包含大量提示、技巧等。mod_rewrite 的一个优点是它不会随着新版本的不断发布而被弃用,因此关于该主题的旧文章仍然完全有效 :-)

不妨孤注一掷,同时提到[TheJackol 上的 mod_rewrite / .htaccess 备忘单,其中有一些有用的快速代码片段和一些信息。

其他网址:

  • perishablepress.com/press/2006/01/10/stupid-htaccess-tricks/
  • thejackol.com/htaccess-cheatsheet/

抱歉,我无法对它们进行超链接,因为我还没有 10 个代表点,所以系统阻止我对这三个进行超链接 :-(

答案3

RewriteCond URL (?!.*/utils).*
RewriteCond URL (?!.*/store).*
RewriteRule (.*) http\://{your new host here}/$3 [I,R]

注意:这是 ISAPI_Rewrite 的语法,它应该与 mod-rewrite 兼容。

相关内容