【问题标题】:Issue while serving file using PHP with xsendfile and custom htaccess file使用带有 xsendfile 和自定义 htaccess 文件的 PHP 提供文件时出现问题
【发布时间】:2018-07-24 18:15:07
【问题描述】:

我在一个需要提供研究论文和文件的项目中工作,因此在提供文件时需要检查几遍,如果一切看起来都不错,那么它应该转发文件(研究论文)。

使用 PHP 读取文件和流式传输很容易,但我们需要使用 apache xsendfile 来提供文件。

应用程序的工作方式不同,但是我做了一个这样的小项目,以便我们可以重现问题。

所有请求都转到一个 IP 地址,并使用.htaccess 文件,它将请求重定向到index.php 文件。

这是 htaccess 文件:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]
XSendFile On

index.php 中,它将决定提供哪个文件。这是index.php的代码:

<?php

  $file = 
    __DIR__ 
    . '/scholar' 
    . $_SERVER[ 'REQUEST_URI' ] 
    . 'index.html';

  // echo $file;
  // exit();

  header("Content-type: " . mime_content_type( basename( $file ) ));
  header("X-Sendfile: " . $file );

$file 变量中,它将生成所请求研究论文的完整路径。

  • 请求的 URL:http://dev.edu/project-1/
  • 生成的文件路径:/var/www/html/scholar/project-1/index.html

这里文件路径有效,但是找不到文件!

虽然错误信息表明没有找到index.php文件,但是如果你取消注释这两行,

  // echo $file;
  // exit();

您将能够看到 index.php 文件实际上已被 apache 使用,它会打印出该文件的完整有效路径!

我已尽力让您了解问题所在,但我无法真正了解导致此问题的原因。

编辑:/var/www/html/的文件夹树

编辑:xsendfile 已安装并启用

【问题讨论】:

  • 编辑您的 .htaccess 以使用 RewriteRule ^scholar$ /scholar/project-1/index.html 指向该文件夹。我假设 /scholar 在根 web 目录中
  • 你没有在某处设置XSendFilePath apache 选项吗?
  • @Alex 我试图在 htaccess 文件中添加它,但它也会失败。
  • 你认为它为什么会失败?

标签: php apache .htaccess x-sendfile


【解决方案1】:

让 .htaccess 为您完成所有工作:

RewriteEngine on
RewriteRule ^project-1$ /scholar/project-1/index.html
RewriteRule ^project-2$ /scholar/project-2/index.html

如果您输入 url http://localhost/project-1,它将引导您到 project-1 的文件夹

我刚刚测试了它。

如果您想在 url 中包含斜杠以避免 404,那么只需更改

    RewriteEngine on
    RewriteRule ^project-1/$ /scholar/project-1/index.html
    RewriteRule ^project-2/$ /scholar/project-2/index.html

【讨论】:

  • 感谢您的回答,可能有数百个项目和文档,因此无法将其映射到 htaccess 文件中
  • 好的,会尝试找到更好的解决方案,我有一些时间
  • @rakibtg 如果您只需要某种重定向 - 您根本不需要使用 SendFile 标头。
  • @Alex 这正是我的想法,您可以让 index.php 映射出所有项目文件夹并将它们显示在 index.php 上,然后只需选择您想要激活的文件夹等跨度>
  • @rakibtg 你试过将`XSendFilePath /path/to/files/directory' 添加到.htaccess
猜你喜欢
  • 1970-01-01
  • 2011-08-18
  • 2019-04-17
  • 1970-01-01
  • 2014-12-29
  • 1970-01-01
  • 2022-06-14
  • 2021-11-27
  • 1970-01-01
相关资源
最近更新 更多