Apache配置對站點目錄的認證

前言:

有的時候需要對站點中的某個目錄進行保護,只有輸入指定的賬號密碼才可以瀏覽。這當然可以透過動態網站設計語言來實現,但透過對Apache本身的配置來實現似乎要更方便一些。

配置方法:

一、Apache配置編輯及站點建立

建立一個站點配置檔案。

[root@localhost auth]# vim /etc/httpd/conf.d/vhost1.conf

內容如下:

<Directory "/tmp/html/auth/">      // 要啟用認證的目錄
    AuthName "請認證身份"           // 伺服器返回的認證對話方塊的標題
    AuthType Basic                 // 認證型別
    AuthUserFile /tmp/html/auth/.htpasswd      // 密碼配置檔案路徑
    require valid-user             // 允許透過認證的所有使用者訪問,如果改為某一使用者名稱則只允許此使用者訪問
</Directory>
<VirtualHost *:80>                 // 建立一個簡單的虛擬主機用於測試
    DocumentRoot /tmp/html/
</VirtualHost>

建立站點執行目錄及要開啟認證的站點子目錄。

[root@hostname ~]# mkdir -p /tmp/html{,/auth}

檢視此時的站點目錄結構。

[root@hostname ~]# tree /tmp/html/
/tmp/html/
└── auth

在站點子目錄下建立首頁檔案。

[root@hostname ~]# echo 'Hello,world!' > /tmp/html/auth/index.html

二、生成使用者密碼配置檔案

建立新檔案,並向其中新增一個使用者認證資訊。

[root@hostname ~]# htpasswd -cb /tmp/html/auth/.htpasswd user1 123456     //-c引數用於建立新檔案,若檔案已存在則無需使用-c引數,-b引數用於指定在命令列中直接鍵入密碼,而不是用互動模式。user1為使用者名稱,123456為密碼。
Adding password for user user1   //提示成功新增了user1的使用者密碼

增加一個新的認證使用者。

[root@hostname ~]# htpasswd -b /tmp/html/auth/.htpasswd user2 123456
Adding password for user user2   //成功新增

修改使用者的密碼。

[root@hostname ~]# htpasswd -mb /tmp/html/auth/.htpasswd user1 654321
Updating password for user user1 //密碼更新成功

刪除認證使用者。

[root@hostname ~]# htpasswd -D /tmp/html/auth/.htpasswd user2
Deleting password for user user1 //刪除成功

測試:

使用瀏覽器訪問http://URL/auth(URL是你網站的域名或IP)就會看到要求認證的對話方塊啦!

這裡我為了方便,使用的是Linux下的Links瀏覽器進行測試的。

正確輸入賬號密碼後,即可看到網頁內容。

Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha Code