htaccess:禁止所有pdf文件,但允许使用php脚本(文件下载脚本)


htaccess: disallow all pdf files but allow from php script (file download script)

我写了一个小的下载脚本来隐藏文件路径,文件"get_file.php"处理所有内容。下一步,我想禁止htaccess通过浏览器直接访问所有pdf文件(如果有人知道文件的确切url),但仍然使用我的"get_file.php"提供对文件的访问。

我试过了:

RewriteEngine on 
RewriteCond %{HTTP_REFERER} !^http://(www'.)?localhost [NC] 
RewriteCond %{HTTP_REFERER} !^http://(www'.)?localhost.*$ [NC] 
RewriteRule '.(pdf)$ - [F]

有什么想法吗?

在.htaccess:顶部尝试此规则

RewriteEngine on 
RewriteCond %{THE_REQUEST} '.pdf[?'s] [NC]
RewriteCond %{HTTP_REFERER} !^http://(www'.)?localhost [NC] 
RewriteRule ^ - [F]

试试这个:

get_file.php

<?php
    // You can add extra codes to get your pdf file name here
    $file = 'file.pdf';
    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($file).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    }
?>

第一步-htaccess-我通常有不同的方法使用FilesMatch:

<FilesMatch "'.pdf$">
    Order allow,deny
    Deny from all
</FilesMatch>

第二步是在你的PHP文件上——你只需要使用本地路径来加载和显示它。。/路径/to/file.pdf以下是如何为客户端导出的示例:pdf文件下载的正确PHP头