【问题标题】:Apache RewriteRules - When would you NOT use the [L] flag?Apache RewriteRules - 你什么时候不使用 [L] 标志?
【发布时间】:2012-07-31 08:55:30
【问题描述】:
我知道 [L] 标志应该停止处理任何进一步的 RewriteRules,但我似乎理所当然地将 [L] 添加到每个 RewriteRule,这几乎是在在线编写 sn-ps 代码和示例。
我真的不明白你什么时候会和不想使用 [L] 标志,因为我写过的所有 RewriteRules 似乎都可以使用或不使用 [L] 标志。
有人可以提供一个需要 [L] 和不应该有 [L] 的规则示例吗?
【问题讨论】:
标签:
.htaccess
mod-rewrite
【解决方案1】:
在我的脑海中,你不想使用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 的一部分)。