【问题标题】:htaccess: disallow all pdf files but allow from php script (file download script)htaccess:禁止所有 pdf 文件,但允许来自 php 脚本(文件下载脚本)
【发布时间】:2016-02-22 15:28:14
【问题描述】:

我写了一个小的下载脚本来隐藏文件路径,文件“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]

有什么想法吗?

【问题讨论】:

    标签: php .htaccess pdf mod-rewrite file-access


    【解决方案1】:

    在您的 .htaccess 顶部尝试此规则:

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

    【讨论】:

    • 打败了我。我已经提出了类似的答案,但是当我看到您的答案时清除了所有内容
    【解决方案2】:

    试试这个:

    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;
        }
    ?>
    

    【讨论】:

      【解决方案3】:

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

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

      第二步是在你的 PHP 文件中——你只需要使用本地路径来加载它并显示它.. /path/to/file.pdf 以下是如何为客户导出它的示例:correct PHP headers for pdf file download

      【讨论】:

        猜你喜欢
        • 2014-11-21
        • 2015-05-17
        • 1970-01-01
        • 1970-01-01
        • 2012-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多