我试图限制直接访问目录中的文件.所以例如我有website.com/files/example.flv.
因此,如果用户直接访问URL中的文件,我希望将它们重定向到主页.
我使用htaccess尝试了以下内容
deny from all
Run Code Online (Sandbox Code Playgroud)
但它的效果不佳.有没有办法我可以用PHP做到这一点,然后在用户直接进入网址中的文件,他们将被重定向.
因此,如果用户转到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);
}
Run Code Online (Sandbox Code Playgroud)
是.您必须将文件放在无法通过Web访问的目录中.然后,您必须在public_html/files /文件夹中创建一个.htaccess文件,该文件指向您的php脚本.
像这样的东西(注意:代码没有经过测试):
结构体:
的.htaccess:
RewriteEngine on
RewriteRule ^/files/(.+)$ filehandler.php?stuff=$1 [QSA]
Run Code Online (Sandbox Code Playgroud)
filehandler.php:
header('Location: /');
Run Code Online (Sandbox Code Playgroud)
当然,当您希望文件访问它们时,您希望可以访问这些文件.这可以在filehandler.php中完成,方法是检查是否允许用户查看文件,然后返回如下内容:
header('Content-type: application/octet-stream');
header('Content-Disposition: inline; filename="'.basename(urlencode($file['name'])).'"');
readfile($dir.basename($file['filename']));
exit;
Run Code Online (Sandbox Code Playgroud)