将整个网站重定向到子文件夹

时间:2016-07-29 19:28:33

标签: .htaccess redirect mod-rewrite web

我不希望我的网站位于我的网站空间的根文件夹中! 这样做的目的是创建一个无法通过网络访问的文件夹(例如安全文件,下载)

我试图重定向,但我不能让它100%工作

示例:

-root
--downloads
--web
---f1
--.htaccess

我的htaccess文件:

<ifmodule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^(.*)$ /web/$1 [L,NC]   
</ifmodule>

这很有效 url.com 会被重定向到 url.com/web ,而不会更改地址行中的网址。

但问题开始了 一旦我尝试访问 url.com/f1 这样的文件夹,它就会被重定向到(并显示为) url.com/web/f1 ,我不想要的在地址栏中显示。

此外,我仍然可以访问 url.com/downloads ,我希望将其重定向到 url.com/web/downloads

有人可以向我解释一下解决这个问题,或者解决这个问题的正确方法。

1 个答案:

答案 0 :(得分:0)

  

这样做的目的是创建一个无法访问的文件夹   网络。(例如安全文件,下载)

因此,对于您的第一个问题,您需要将文件夹移到根目录之外。这是使它们安全的最佳方式。有这样的结构。

--downloads
--f1
--root
  -- web

然后绝对没有办法在浏览器中找到它并且你不需要为此重写。

现在,您只需使用后端代码检索文件,然后允许用户在获得授权后下载该文件。你没有说出你使用的是什么,我将提供一个PHP示例。

然后,您可以使用此类代码强行下载。您可以使用以下链接获取完整示例,也可以使用DB。

<?php

ignore_user_abort(true);
set_time_limit(0); // disable the time limit for this script

$path = "/home/username/downloads/"; // change the path to fit your websites document structure

$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;

if ($fd = fopen ($fullPath, "r")) {
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) {
        case "pdf":
        header("Content-type: application/pdf");
        header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
        break;
        // add more headers for other content types here
        default;
        header("Content-type: application/octet-stream");
        header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
        break;
    }
    header("Content-length: $fsize");
    header("Cache-control: private"); //use this to open files directly
    while(!feof($fd)) {
        $buffer = fread($fd, 2048);
        echo $buffer;
    }
}
fclose ($fd);
exit;

http://www.web-development-blog.com/archives/php-download-file-script/

相关问题