mod_rewrite下载 - 制作可疑的文件

时间:2012-05-25 12:00:06

标签: .htaccess mod-rewrite download

我决定尝试使用mod_rewrite来隐藏用户可以下载的文件的位置。

所以他们点击一个指向“/ download / some_file /”的链接,然后他们改为“/downloads/some_file.zip”

像这样实施:

RewriteRule ^download/([^/\.]+)/?$ downloads/$1.zip [L]

除了下载进度出现之外,它的工作原理我正在获取一个文件“下载”,没有看起来可疑的扩展名,用户可能不知道他们应该解压缩它。有没有办法这样做它看起来像一个实际的文件?或者有更好的方法我应该这样做吗?

提供隐藏文件位置的一些上下文/原因。这是一个乐队,可以免费下载音乐,前提是用户注册邮件列表。

我也不需要在.htaccess

中执行此操作

2 个答案:

答案 0 :(得分:1)

您可以通过发送Content-disposition标题来设置文件名:

https://serverfault.com/questions/101948/how-to-send-content-disposition-headers-in-apache-for-files

答案 1 :(得分:0)

好的,所以我相信我使用.htaccess

限制了我可以设置的标题

所以我用PHP解决了这个问题。

我最初复制了一个下载的PHP脚本: How to rewrite and set headers at the same time in Apache

但是我的文件太大,因此无法正常工作。

经过一段谷歌搜索后,我遇到了这个问题:http://teddy.fr/blog/how-serve-big-files-through-php

所以我的完整解决方案如下......

首先发送下载脚本请求:

RewriteRule ^download/([^/\.]+)/?$ downloads/download.php?download=$1 [L]

然后获取完整的文件名,设置标题,并按块提供块:

<?php
if ($_GET['download']){
  $file = $_SERVER['DOCUMENT_ROOT'].'media/downloads/' . $_GET['download'] . '.zip';
}

define('CHUNK_SIZE', 1024*1024); // Size (in bytes) of tiles chunk

// Read a file and display its content chunk by chunk
function readfile_chunked($filename, $retbytes = TRUE) {
    $buffer = '';
    $cnt =0;
    // $handle = fopen($filename, 'rb');
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
      return false;
    }

    while (!feof($handle)) {
        $buffer = fread($handle, CHUNK_SIZE);
        echo $buffer;
        ob_flush();
        flush();
        if ($retbytes) {
            $cnt += strlen($buffer);
        }   
    }
    $status = fclose($handle);
    if ($retbytes && $status) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;
}

$save_as_name = basename($file);   
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: no-cache');
header("Content-Type: application/zip");
header("Content-Disposition: disposition-type=attachment; filename=\"$save_as_name\"");

readfile_chunked($file); 
?>