【问题标题】:Why does mod_rewrite ignore my [L] flag?为什么 mod_rewrite 会忽略我的 [L] 标志?
【发布时间】:2013-12-15 13:02:47
【问题描述】:

这是我的.htaccess 文件。如果 url 匹配它们,它应该从 assets 文件夹传递静态文件。否则,一切都应该重定向到index.php

请注意,此处的 url 不包含 assets 作为 segemnt。所以example.com/css/style.css 指向assets/css/style.css

RewriteEngine on

# disable directory browsing
Options -Indexes

# static assets
RewriteCond %{DOCUMENT_ROOT}/assets/$1 -f
RewriteRule ^(.*)$ assets/$1 [L]

# other requests to index.php
RewriteRule !^asset/ index.php [L]

不幸的是,像 example.com/assets/css/style.css 这样的 url 也会传递文件,因为对于那个 url,我的规则都不适用,并且应用了 Apache 的默认行为来传递文件。

所以我尝试将最后一行更改为此。我认为这会起作用,因为上述规则中的 [L] 标志应该停止执行资产 URL 并传递它们。

RewriteRule ^(.*)$ index.php [L]

相反,并非所有请求都被重定向到index.php,即使是像example.com/css/style.css 这样的静态资产。为什么 flag 不停止执行重写规则以及谁来解决我的问题?

【问题讨论】:

    标签: apache mod-rewrite redirect web-applications assets


    【解决方案1】:

    我在official documentation的页面上找到了解决方案。

    如果您在 .htaccess 文件或 部分,重要的是有一些了解 如何处理规则。这个的简化形式是,一旦 规则已处理,重写的请求返回给 URL 解析引擎用它来做它可能做的事情。它可能是 在处理重写的请求时,.htaccess 文件或 部分可能会再次遇到,因此可以运行规则集 再次从头开始。最常见的情况是,如果其中一个 规则导致重定向 - 无论是内部的还是外部的 - 导致 请求流程重新开始。

    因此,如果您在 这些上下文之一,您采取明确的步骤来避免规则 循环,而不是仅仅依靠 [L] 标志来终止执行 一系列的规则,如下图。

    另一个标志 [END] 不仅可以用来终止 当前轮的重写处理,但防止任何后续重写 在每个目录(htaccess)上下文中发生的处理。这 不适用于由外部重定向产生的新请求。

    为了解决我的问题,我将[L] 标志更改为[END]

    RewriteEngine on
    
    # disable directory browsing
    Options -Indexes
    
    # static assets
    RewriteCond %{DOCUMENT_ROOT}/assets/$1 -f
    RewriteRule ^(.*)$ assets/$1 [END]
    
    # other requests to index.php
    RewriteRule !^asset/ index.php [END]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 2012-07-14
      • 2023-04-01
      • 2012-10-05
      • 1970-01-01
      • 2017-02-11
      相关资源
      最近更新 更多