建立 .htacces 档案
基本(Basic) 验证是目前最为广泛使用的方法,以下例子会替 /var/www/html/dir_protect 加入密码保护,请先在这目录建立一个 .htaccess 的档案,然后加入以下内容:
|
1 2 3 4 5 6 |
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 — 储存登入帐号的档案。
— 限制所有 GET 及 POST 方法。
require valid-user — 合法使用者可以存取目录。
建立 .htpasswd 档案
下一步是建立 .htpasswd 档案。因为 .htpasswd 档案内每一行代表一组帐号,格式为:
username:password
但里面的密码是经过编码的,所以不能直接编码,需要使用 apache 内建的 htpasswd 来做,以下是建立方法:
|
1 2 3 4 |
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 档案,并加入以下内容:
|
1 2 3 |
<Directory "/var/www/html/dir_protect"> AllowOverride All </Directory> |
备注: AllowOverride All 代表可以在 .htaccess 档案使用任何指令。
编辑好 httpd.conf 后需要重新启动 apache。
使用 PHP 建立 .htpasswd
以上是通过 apache 内建的 htpasswd 程式来做,而使用 php 同样可以做到,但在执行时请注意,apache 对 /var/www.html/dir_protect/.htpasswd 要有写入权限,方法如下:
|
1 2 3 4 5 6 7 8 9 10 11 |
<?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。