Apache 目錄級存取控制需三個要素:
htpasswd 產生,儲存帳號與雜湊密碼。.htaccess,定義驗證方式與允許名單。httpd.conf 需設定 AllowOverride AuthConfig 才讀取 .htaccess。htpasswd -c /data/httpd/secr/.htpasswd user1
# 輸入密碼兩次,-c 為建立新檔(後續新增用戶勿加 -c)
vi /var/www/html/private/.htaccess
# 內容:
AuthName "My Private Area"
AuthType Basic
AuthUserFile /data/httpd/secr/.htpasswd
Require user user1
chmod 644 /data/httpd/secr/.htpasswd /var/www/html/private/.htaccess
# 確保 Apache 執行身分(www-data/httpd)可讀取
vi /etc/httpd/conf/httpd.conf
# 找到對應 區塊或新增:
Options Indexes FollowSymLinks
AllowOverride AuthConfig
Require all granted
重新載入 Apache:systemctl reload httpd 或 apachectl graceful。
htpasswd /home/httpd/secr/.htpasswd m1 # 輸入 m1pass
htpasswd /home/httpd/secr/.htpasswd m2 # 輸入 m2pass
.htgroupvi /home/httpd/secr/.htgroup
# 內容:
myfriends: m1 m2
vi /home/httpd/html/backup/.htaccess
AuthName "My Friends Only"
AuthType Basic
AuthUserFile /home/httpd/secr/.htpasswd
AuthGroupFile /home/httpd/secr/.htgroup
Require group myfriends
用戶超過數百時,文字檔查找緩慢。可用 htdbm 建立資料庫:
htdbm -c -T db /data/httpd/secr/users.dbm user1
# .htaccess 改用:
AuthBasicProvider dbm
AuthDBMUserFile /data/httpd/secr/users.dbm
AuthType Digest、htdigest),密碼不以明文/基礎編碼傳輸。mod_evasive 或 fail2ban 封鎖 IP。500 Internal Server Error:檢查 AllowOverride 是否設定、.htaccess 語法、檔案路徑權限。AuthUserFile 路徑錯誤、Apache 無讀取權限。AuthGroupFile 路徑、群組檔格式(冒號分隔、成員以空格分隔)。