.htaccess - 图像文件被视为 PHP 文件

.htaccess - image filed treated as PHP file

我编写了一个简单的 PHP REST 应用程序,但在提供静态文件时遇到问题。我的目录结构如下所示:

我的项目中有两个 .htaccess 文件 - 在根目录和 public 目录中:

root .htaccess

RewriteEngine on
RewriteRule    ^$    public/    [L]
RewriteRule    (.*) public/    [L]

public .htaccess(标准 Slim 模板)

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA]

这些配置看起来像那样,因为我希望将所有请求重定向到 public 目录,并在请求 uri 中省略该部分以具有 http://host.com/rest/XXX instead http://host.com/rest/public/XXX.

现在我无法使用 http://host.com/rest/content/file-test.ext 访问文件 - 它似乎被视为 PHP 文件,因为我收到错误:

Warning: Unexpected character in input: '' (ASCII=30) state=0 in /rest/public/content/file-test.ext on line 298

Parse error: syntax error, unexpected '@' in /rest/public/content/file-test.ext on line 298

我已经尝试使用 RewriteEngine offphp_flags engine off.

将单独的 .htaccess 文件放入内容目录中

我无法更改任何网络服务器配置,因为托管是由第 3 部分人员提供的,我什至无法请求任何更改。 host.com/rest 我设置为我的文档根目录,当我通过 FTP 连接时,我无法从该目录向上移动,因此关于网络服务器配置更改的解决方案在我的情况下不正确。

请帮助我使静态文件正常工作!

利用 Slim:它保留在您手中的控制权,您不会用 .htaccess 解决问题。

另外:

  • 您可以随时更改路径或包含的文件夹。
  • 您可以设置额外的 headers 例如用于缓存。
$app->get('/content/{pathToImage}', function($request, $response, $args) {
    $pathToFile = $args['pathToImage'];
    $containingFolder = '../content/'; // the actual folder where files are stored
    // if you want to omit file extension in the url, we'll have to find it out
    $matches = glob($containingFolder.$fileName.'.*');
    if ($matches) {
        $clientImagePath = array_shift($matches); // let's grab the first file matching our mask
        $clientImage = @file_get_contents($clientImagePath);
        $finfo = new \Finfo(FILEINFO_MIME_TYPE);
        $response->write($clientImage);
        return $response->withHeader('Content-Type', $finfo->buffer($clientImage));
    } else {
        // if no matches found, throw exception that will be handled by Slim
        throw new \Slim\Exception\NotFoundException($request, $response);
    }
});

如果您可以接受像 content/image.png 这样的 URL(具有文件扩展名),您可以通过更简单的方式执行此操作:

$app->get('/assets/images/{pathToImage}', function($request, $response, $args) {
    $pathToFile = $args['pathToImage'];
    $path = '../content/'.$fileName;
    $image = @file_get_contents($path);
    $finfo = new \Finfo(FILEINFO_MIME_TYPE);
    $response->write($image);
    return $response->withHeader('Content-Type', $finfo->buffer($image));
});