我试图限制对目录中文件的直接访问。例如,我有 website.com/files/example.flv。
因此,如果用户直接访问 URL 中的文件,我希望他们被重定向到主页。
我使用 htaccess 尝试了以下操作
deny from all
但它不是很好。有没有办法我可以使用 php 来做到这一点,然后在用户直接进入 url 中的文件时,他们将被重定向。
因此,如果用户转到 url 中的文件链接,他们将被发送到主页。那么这只能使用htaccess来完成吗
如果你想限制对文件的访问,你应该考虑将它们存储在公共 DocumentRoot 之外,并使用 PHP 来传递文件,应用你自己的访问逻辑。这意味着在 www 或 public_html 文件夹之外,具体取决于您使用的托管环境。
<?php
// Suppose your "public_html" folder is .
$file = './../data/test.gif';
$userCanDownloadThisFile = false; // apply your logic here
if (file_exists($file) && $userCanDownloadThisFile) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=filename.gif');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
}
是的。您必须将文件放在无法通过网络访问的目录中。然后,您必须在 public_html/files/ 文件夹中创建一个 .htaccess 文件,该文件指向您的 php 脚本。
像这样的东西(注意:代码未经测试):
结构:
.ht 访问:
RewriteEngine on
RewriteRule ^/files/(.+)$ filehandler.php?stuff=$1 [QSA]
文件处理程序.php:
header('Location: /');
当然,当您希望文件访问它们时,您会希望它们可以访问。这可以在 filehandler.php 中完成,方法是检查是否允许用户查看文件,然后返回如下内容:
header('Content-type: application/octet-stream');
header('Content-Disposition: inline; filename="'.basename(urlencode($file['name'])).'"');
readfile($dir.basename($file['filename']));
exit;