基本(Basic) 驗證是目前最為廣泛使用的方法,以下例子會替 /var/www/html/dir_protect 加入密碼保護,請先在這目錄建立一個 .htaccess 的檔案,然後加入以下內容:
CODE:
[Copy to clipboard]
AuthName "Member Only"
AuthType Basic
AuthUserFile /var/www.html/dir_protect/.htpasswd
<Limit GET POST>
require valid-user
</Limit>
以上段落的意思為:
AuthName "Member Only" -- 密碼保錄目錄名稱,這裡可自行修改。
AuthType Basic -- 使用基本驗證方法。
AuthUserFile /var/www.html/dir_protect/.htpasswd -- 儲存登入帳號的檔案。
<Limit GET POST> -- 限制所有 GET 及 POST 方法。
require valid-user -- 合法使用者可以存取目錄。
建立 .htpasswd 檔案
下一步是建立 .htpasswd 檔案。因為 .htpasswd 檔案內每一行代表一組帳號,格式為:
username:password
但裡面的密碼是經過編碼的,所以不能直接編碼,需要使用 apache 內建的 htpasswd 來做,以下是建立方法:
CODE:
[Copy to clipboard]
touch /var/www.html/dir_protect/.htpasswd
htpasswd -m /var/www.html/dir_protect/.htpasswd auth_user
New password: 輸入密碼
Re-type new password: 再次輸入密碼確認
如果發目錄內加入了 .htaccess 及 .htpasswd 兩個檔案後未能有密碼保護功能,便需要編輯 apache 的 httpd.conf 檔案,並加入以下內容:
CODE:
[Copy to clipboard]
<Directory "/var/www/html/dir_protect">
AllowOverride All
</Directory>
P.S. AllowOverride All 代表可以在 .htaccess 檔案使用任何指令。
編輯好 httpd.conf 後需要重新啟動 apache。
使用 PHP 建立 .htpasswd
以上是通過 apache 內建的 htpasswd 程式來做,而使用 php 同樣可以做到,但在執行時請注意,apache 對 /var/www.html/dir_protect/.htpasswd 要有寫入權限,方法如下:
CODE:
[Copy to clipboard]
<?php
$username = "admin";
$password = "passwd";
// make password string
$crypt_str = $username . ":" . crypt( $newpass, "MM");
$fp = fopen("/var/www.html/dir_protect/.htpasswd", "a+");
fputs( $fp, $crypt_str."\n");
fclose( $fp);
?>
以上程式會建立 admin 帳號,密碼是 passwd。