【问题标题】:Ignore files in non-existent paths using .htaccess使用 .htaccess 忽略不存在路径中的文件
【发布时间】:2014-03-31 13:50:15
【问题描述】:

我在重写时遇到问题。 这是我的 .htaccess 文件

RewriteEngine On
RewriteBase /
#ignore non-existent utility-files 
RewriteCond %{REQUEST_FILENAME} \.(gif|jpe?g|s?html|css|js|cgi|png|ico|txt)$ 
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d 

RewriteRule .* - [L]

#load existent utility files and don't rewrite them to index.php
RewriteCond %{REQUEST_FILENAME} \.(gif|jpe?g|s?html|css|js|cgi|png|ico|txt)$
RewriteRule ^(.*) $1 [L]
#load other files if they exist
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*) $1 [L]
#load index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]

最后一部分正在工作,但我想避免在代码请求不存在的图像时加载我的 index.php(如:www.mysite.test/images/foobar.png

第一个 RewriteCond-Line 应该检查请求是否匹配图像、JavaScript 等文件,第二个 RewriteCond 行应该检查该文件是否不存在。 第三个应该检查文件夹是否存在。 如果匹配成功,则不应加载任何内容。

它有效,但前提是该文件夹存在。如果图像不存在的文件夹则不起作用。

【问题讨论】:

    标签: apache file .htaccess mod-rewrite


    【解决方案1】:

    你有很多多余的规则。您可以简化为:

    RewriteEngine On
    RewriteBase /
    
    #ignore non-existent utility-files 
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} \.(gif|jpe?g|s?html|css|js|cgi|png|ico|txt)$ [NC]
    RewriteRule ^ - [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php [L]
    

    【讨论】:

    • 问题是当PATH不存在时它不起作用
    • 当它的图像和路径不存在时,它将转到正常的 404 方式
    • 不,如果路径不存在,则调用 index.php。示例:如果 mydomain.test/images/ 不存在,mydomain.test/images/image.png 加载 index.php。如果 PATH mydomain.test/img/ 但图像 mydomain.test/img/foo.png 不存在。重写按预期工作 - 即没有加载任何内容。
    • 这是不正确的。我测试了这些确切的规则,mydomain.test/foo.jpg 生成 404 而不是加载 index.php 你确定没有任何其他规则或任何其他 .htaccess 文件吗?
    • 我找到了解决方案。我将其发布在原始问题中,因为我无法发布自己问题的答案。
    【解决方案2】:

    好的,正如成员 anubhava 所说,现有文件仍然存在问题。 我的最终解决方案是:

    <IfModule mod_security.c>
    SecFilterEngine Off
    SecFilterScanPOST Off
    </IfModule>
    RewriteEngine On
    RewriteBase /
    
    #load files if they exist
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^(.*) $1 [L]
    
    #ignore non-existent utility-files 
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule \.(gif|jpe?g|s?html|css|js|cgi|png|ico|txt|php)$ - [L]
    
    #load index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php [L]
    

    此解决方案在第二个重写规则中包含 php 文件。因为我有一些实际上是 css 文件并由浏览器加载的 php 文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 2011-01-20
      • 2021-12-28
      • 2015-09-05
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      相关资源
      最近更新 更多