2013年6月30日 星期日

apache 利用.htaccess來控管目錄存取

做法是使用rewrite module把網頁存取的行為 導到php來檢查權限


1. load module
     可以在/etc/apache2/httpd.conf中加入以下這一行就可以把rewrite module弄起來 (/usr/lib/apache2/module/mod_rewrite.so可能隨著系統不同路徑會不同)
     LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so
2. 注意AllowOverride屬性
     如果要管控特定目錄 必須要確保該目錄上層的.htaccess有開放Override 不然就有可能白寫.htaccess
3. 在想要管控的目錄中的 .htaccess 加入以下幾行
     Options +FollowSymLinks
     RewriteEngine on
     RewriteRule ^(.*)$ ../authorize.php?file=$1
   
    藉著以上三行 一但有任何存取該目錄的行為 就會跑進上一層目錄下的 authorize.php



以下則是authorize.php的範例
採用wordpress的登入與否來決定是否開放權限給人下載

++require('../wp-blog-header.php');
+
+
+if(is_user_logged_in()){
+       header('Content-type:application/force-download');
+       header('Content-Transfer-Encoding: Binary');
+       header('Content-Disposition:attachment;filename='.$_REQUEST['file']);
+       readfile($_REQUEST['folder'].'/'.$_REQUEST['file']);
+}
+else{
+       echo "Please login before access this file\n";
+}
+?>