9

我知道 [L] 标志应该停止处理任何进一步的 RewriteRules,但我似乎理所当然地将 [L] 添加到每个 RewriteRule 中,这几乎是代码片段和网上的例子。

我真的不明白你什么时候会和不想使用 [L] 标志,因为看起来我写过的所有 RewriteRules 都可以使用或不使用 [L] 标志。

有人可以提供一个需要 [L] 和不应该有 [L] 的规则的示例吗?

4

1 回答 1

12

在我的脑海中,你不想使用的时候L

  • 当您需要使用N标志循环重写时

    # Replace all instances of "aaa" with "zzz"
    RewriteRule ^(.*)aaa(.*)$ /$1zzz$2 [N]
    
  • 当您使用C标志将一组重写逻辑链接在一起时

    # replace "old" with "new" but only if the first rule got applied
    RewriteRule ^special/(.*)$ /chained/$1 [C]
    RewriteRule ^(.*)/old/(.*)$ /$1/new/$2 [L]
    
  • 当您需要使用S标志跳过一些规则时(取自 apache 文档,因为我想不出一个工作示例)

    # Is the request for a non-existent file?
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    # If so, skip these two RewriteRules
    RewriteRule .? - [S=2]
    
    RewriteRule (.*\.gif) images.php?$1
    RewriteRule (.*\.html) docs.php?$1
    
  • 当您想要重定向但需要在使用R标志重定向之前让其他规则处理 URI 时

    # If host is wrong, redirect
    RewriteCond %{HTTP_HOST} bad.host.com
    RewriteRule ^stuff/(.*)$ http://good.host.com/$1 [R=301]
    
    # but not until we apply a few more rules
    RewriteRule ^(.*)/bad_file.php$ /$1/good_file.php [L]
    

另一方面,有时L不需要使用该标志,但它确保在应用该规则时停止重写。它只是让制定规则更容易,因为它可以防止不同的规则集相互干扰,所以在所有规则的末尾无害地包含一个标志通常是安全的L,因为 99%时间,你真的只想停在那里。

请注意,L仅停止当前迭代的重写。重写引擎将循环,直到进入引擎的 URI 与输出的 URI 完全相同(查询字符串不是 URI 的一部分)。

于 2012-08-02T12:42:04.713 回答