Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

Apache 基礎認證完整實作:htpasswd 建立、.htaccess 配置、效能考量與進階替代方案

編輯:關於伺服器

適用場景

  • 保護後台管理介面、測試環境、內部文件、API 端點
  • 輕量級、無需資料庫、跨平台相容
  • 不適用:高併發、頻繁帳號異動、SSO 整合、精細權限控制 (RBAC/ABAC)

步驟 1:建立受保護目錄


mkdir -p /var/www/html/protected
chown -R apache:apache /var/www/html/protected

步驟 2:修改 httpd.conf 啟用 AllowOverride AuthConfig



    Options Indexes FollowSymLinks
    AllowOverride AuthConfig
    Require all granted

關鍵:AllowOverride AuthConfig 允許 .htaccess 覆蓋認證設定。生產環境建議直接在 httpd.conf 或 vhost.conf 內配置 <Directory> 區塊,避免每次請求掃描 .htaccess 影響效能。

步驟 3:建立 .htaccess 定義認證規則


# /var/www/html/protected/.htaccess
AuthName "Internal Admin Area"
AuthType Basic
AuthUserFile /etc/httpd/.htpasswd_admin
Require valid-user
# 或限定用戶:Require user alice bob

步驟 4:建立密碼檔與帳號 (htpasswd)


# 首次建立 (-c 建立新檔),使用 bcrypt (-B) 或 SHA256 (-s)
htpasswd -cB /etc/httpd/.htpasswd_admin alice
# 新增用戶 (不加 -c)
htpasswd -B /etc/httpd/.htpasswd_admin bob
# 修改密碼
htpasswd -B /etc/httpd/.htpasswd_admin alice
# 刪除用戶
htpasswd -D /etc/httpd/.htpasswd_admin bob
# 列出用戶
htpasswd -v /etc/httpd/.htpasswd_admin alice

安全建議:密碼檔置於 DocumentRoot 之外 (如 /etc/httpd/),檔名以 .ht 開頭 (Apache 預設拒絕存取)。權限 640 root:apache。

步驟 5:重啟驗證


systemctl reload httpd
# 瀏覽器訪問 https://server/protected/ 應彈出基本認證對話框

進階:群組授權 (AuthGroupFile)


# /etc/httpd/groups
admins: alice bob charlie
developers: david eve

# .htaccess
AuthGroupFile /etc/httpd/groups
Require group admins

效能影響與優化

安全加固清單

  • ✅ 全站強制 HTTPS (Basic Auth 明文傳輸 Base64 易竊聽)
  • ✅ 密碼複雜度策略 (長度 ≥ 12、混合字元、定期輪換)
  • ✅ 失敗嘗試限制:mod_evasive / fail2ban 監控 401 狀態碼
  • ✅ 敏感目錄雙重保護:IP 白名單 + 基礎認證
  • ✅ 定期審核帳號清單、移除離職/專案結束帳號

現代替代方案速查

  • nginx:auth_basic + auth_basic_user_file (語法類似、效能更高)
  • 應用層認證:JWT/OAuth2/OIDC (Keycloak/Auth0/Authelia) — 統一、可撤銷、支援 MFA
  • 反向代理認證:Authelia/Traefik ForwardAuth/oauth2-proxy — 統一在入口驗證,後端零侵入
Copyright © Windows教程網 All Rights Reserved
配置方式效能影響建議場景
.htaccess + AllowOverride每請求向上遞歸掃描 .htaccess,額外 syscall、I/O共享主機、無 httpd.conf 寫入權限、臨時測試
httpd.conf/vhost.conf 啟動時讀取一次,無運行期額外開銷生產環境、自有伺服器、高併發
mod_auth_dbd / mod_authn_dbd資料庫查詢開銷,可配合連線池帳號頻繁異動、需即時生效、整合現有用戶庫
mod_authnz_ldap / mod_auth_kerbLDAP/Kerberos 查詢延遲,支援 SSO企業 AD/LDAP 整合、單點登入