【问题标题】:.htaccess RewriteCond for images in another folder.htaccess RewriteCond 用于另一个文件夹中的图像
【发布时间】:2014-10-07 02:52:35
【问题描述】:

是的,又是一个 RewriteCond,但我正在努力让它发挥作用....

我的 Apache 根为 /var/www/html/,如果我转到 http://example.com/,它会正确使用 /var/www/html/index.php

现在,问题是我在/var/www/images/example.com/ 中有图像。这是因为我有一个需要动态的多站点设置。 PHP 将整理出使用了哪个站点的代码,因此移动图像或为它们加上别名不是一种选择,因为它需要是动态的。

所以,我的/var/www/html/.htaccess 中有这样的内容:

Options -MultiViews -Indexes

RewriteEngine on

RewriteCond /var/www/images/example.com%{REQUEST_URI} -f
RewriteRule ^(.+)$ /var/www/images/example.com/$1 # <--- this DOES fire when the image exists

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /var/www/html/test.php?file=%{REQUEST_FILENAME} [END]

test.php 只是呼应$_GET,奇怪的是$_GET['file']/var/www/html/var

我做错了什么?!


更新

好的,现在我有了这个:

RewriteCond %{REQUEST_URI} !^/sites/
RewriteRule ^(.*)$ sites/%{HTTP_HOST}/$1 [NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php

我对其进行了更改,以便站点文件位于主服务器根目录中。现在我不能让它不允许直接访问文件。

我想要的是这个:

http://example.com/images/fb.png -> /var/www/sites/example.com/images/fb.png http://example.com/sites/example.com/images/fb.png -> /var/www/index.php(显示 404) http://example.com/whatever -> /var/www/index.php

如您所见,第二行文件是文件的完整直接路径,应该传递给 index.php,但它只是发送文件。如何防止这种情况发生?

【问题讨论】:

    标签: apache .htaccess


    【解决方案1】:

    您不能重写到不在文档根目录中的内容(出于明显的安全原因,否则人们只会注入内容以重写到 /etc/passwd)。这意味着你不能对不在/var/www/html/ 中的任何东西做任何事情。您需要做的是使用可以访问文档根目录之外的文件的脚本。可能是这样的:

    RewriteCond /var/www/images/example.com%{REQUEST_URI} -f
    RewriteRule ^(.+)$ /image_serve.php?img=example.com/$1 [L]
    

    然后,image_serve.php 脚本会执行以下操作:

     <?php
      if (substr($_GET['img'], -strlen('.png')) === '.png')
        header("Content-Type: image/png");
      else if (substr($_GET['img'], -strlen('.gif')) === '.gif')
        header("Content-Type: image/gif");
      else if (substr($_GET['img'], -strlen('.jpg')) === '.jpg')
        header("Content-Type: image/jpeg");
    
      readfile('/var/www/images/' . $_GET['img']);
    ?> 
    

    【讨论】:

    • 好的,这就解释了。
    • 但是,我不想对每个图像都使用 PHP,因为让 APACHE 加载它们要快得多。我会想办法的,谢谢。
    • 即使将图像移动到/var/www/html/ 后,我仍然会遇到同样奇怪的重定向问题。
    • @Sarke 什么重定向问题?
    • /var/www/html/var 问题。我想我已经弄清楚了,如果可行,我会发布我的答案。
    【解决方案2】:

    这就是我想要的。

    # rewrite to site subfolder
    RewriteRule ^(.*)$ sites/%{HTTP_HOST}/$1 [NC,QSD,DPI]
    
    # if file doesn't exists in subfolder, just pass it to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . index.php [END]
    
    # prevent another go-around
    RewriteRule .* - [END]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 2022-10-07
      • 1970-01-01
      • 2013-03-25
      相关资源
      最近更新 更多