【问题标题】:Apache RewriteRule Regex IssueApache RewriteRule 正则表达式问题
【发布时间】:2012-06-27 23:26:45
【问题描述】:

http://httpd.apache.org/docs/2.2/rewrite/intro.html 说:

在 mod_rewrite 中,! 字符可以在正则表达式之前使用来否定它。也就是说,一个字符串只有在与表达式的其余部分不匹配时才会被认为是匹配的。

但是,我的配置仅适用于第一条规则,不适用于第二条。谁能告诉我为什么?

RewriteCond %{HTTP_HOST} !^static\.example\.com
RewriteCond %{HTTP_HOST} ^host\.example\.com
RewriteRule ^(/global/.*)$ /dir1
RewriteRule !^(/global/.*)$ /dir2    #this rule doesn't work.

【问题讨论】:

  • 为什么不使用 .* 代替,因为您的第二个正则表达式将匹配第一个正则表达式未匹配的任何内容?
  • RewriteCond 仅适用于它上面的直接规则。这是您的预期行为吗?此外,如果您在/dir1 重定向上设置[L] 标志,那么您可以使用@flec 的建议。
  • 你能发布第二条规则不起作用的 URL 吗?该规则在哪里使用(.htaccess 或 httpd.conf)?
  • 我尝试了@flec 的建议。它适用于 host.example.com,但 example.com/uri 也将被重写。这不是我想要的。我基本上有一个 *.example.com 的通配符域配置,我只想重写 host.example.com。其他 url 仍然会转到 DocumentRoot。
  • 我正在使用虚拟主机部分中的规则(不在 .htaccess 中)。 服务器名称 example.com ... 。 *.example.com 指向 example.com。

标签: regex apache mod-rewrite


【解决方案1】:

实际上,我通过将规则一分为二来解决这个问题。 host.example.com 和 example.com 都可以正常工作。

RewriteCond %{HTTP_HOST} !^static\.example\.com
RewriteCond %{HTTP_HOST} ^host\.example\.com
RewriteRule ^(/global/.*)$ /dir1 [L]

RewriteCond %{HTTP_HOST} !^static\.example\.com
RewriteCond %{HTTP_HOST} ^host\.example\.com
RewriteRule ^(.*)$ /dir2 [L]

但是我仍然想知道如何使用“!”在重写规则中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2011-01-25
    相关资源
    最近更新 更多