【问题标题】:Cascading resource selection using mod_rewrite使用 mod_rewrite 进行级联资源选择
【发布时间】:2009-11-02 06:13:31
【问题描述】:

我正在考虑设置一个应用程序,其中有一个核心和一个项目命名空间,其中核心是项目定制的默认后备。为此,我希望能够级联各种资源,如 css、javascript 等,出于 excersize 的目的,我将其简化为

./.htaccess
./first/firstonly.txt
./first/both.txt
./second/secondonly.txt
./second/both.txt

预期的行为是一个请求会先检查是否存在,然后再查看第二个,最后抛出 404。

对于 baseurl/firstonly.txt 将命中 ./first/firstonly.txt (200),
而 baseurl/secondonly.txt 会尝试 ./first/secondonly.txt (404) 然后 ./second/secondonly.txt (200)。
baseurl/both.txt 将点击 ./first/both.txt (200) 并且不再继续。
baseurl/nonexistant.txt (404) 将通过级联运行并返回 404。

我对 mod_rewrite 相当精通,所以这里没有必要谈论基础知识。实现这一点的最有效(理智)方式是什么?抛开速度问题不谈,因为大多数情况下,第一次点击就会发现。

【问题讨论】:

    标签: php apache mod-rewrite


    【解决方案1】:

    试试这些规则:

    RewriteEngine on
    RewriteRule ^(first|second)/ - [L]
    RewriteCond %{DOCUMENT_ROOT}/first/$0 -f
    RewriteRule ^[^/]+$ first/$0 [L]
    RewriteCond %{DOCUMENT_ROOT}/second/$0 -f
    RewriteRule ^[^/]+$ second/$0 [L]
    

    【讨论】:

    • 啊,是的,这与我自己提出的解决方案非常相似,但是它依赖于项目的根目录位于文档根目录中,这并不总是发生。它需要能够相对于 .htaccess 愉快地工作(这是当前的症结所在)
    • @devians:改用RewriteCond first/$0 -F
    • 像这样进行 rewritecond 检查似乎不起作用,它需要完整路径
    • @devians:注意-F中的大写F
    【解决方案2】:

    其他一些潜在的解决方案

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !^first
    RewriteCond %{REQUEST_URI} !^second
    RewriteRule ^([^/]+\.?[^/])*$ first/$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !^second
    RewriteRule ^first/([^/]+\.?[^/])*$ second/$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !^(first|second).*$
    RewriteRule .* /404.html [L]
    

    RewriteCond %{REQUEST_URI} 404.html
    RewriteRule .* - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !^first
    RewriteCond %{REQUEST_URI} !^second
    RewriteRule ^([^/]+\.?[^/])*$ first/$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !^second
    RewriteRule ^first/([^/]+\.?[^/])*$ second/$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !^(first|second).*$
    RewriteRule .* /404.html [L]
    

    在我的个人测试中,我注意到 -f 检查仅针对完整路径名是准确的,如果您不在文档根目录中,这会使事情变得棘手。这可以通过重写文件,然后在 request_uri 上执行 -f 来解决吗?

    【讨论】:

      【解决方案3】:
      RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
      RewriteRule ^Public/(.*)$ Application/Public/$1 [L]
      
      RewriteCond %{ENV:REDIRECT_STATUS} 200
      RewriteRule .* - [L]
      
      RewriteRule ^(css|scripts|images|assets|flash)/(.*)$ Public/$1/$2 [L]
      

      这是最终的工作解决方案(在上面的沙盒示例之外)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-15
        • 1970-01-01
        • 1970-01-01
        • 2020-10-28
        • 1970-01-01
        • 1970-01-01
        • 2020-05-07
        相关资源
        最近更新 更多