[教學]對網頁啟用密碼驗證 (Apache)

前一篇已經教學了如何在Nginx中對網頁設定Password Authentication,而並非全部的人都使用Nginx,這篇教大家如何在Apache伺服器設定Password Authentication。

步驟一、產生htpasswd

首先需要產生htpasswd檔案供驗證密碼使用 共有兩種產生方式

第一種方法 透過openssl passwd產生密碼

這方法不需要額外安裝其他程式就可以使用

首先輸入以下指令(其中/etc/apache2/.htpasswd為檔案產生位置 username001為使用者名稱):

sudo sh -c "echo -n 'username001:' >> /etc/apache2/.htpasswd"

接著輸入以下指令來產生密碼(會提示需要輸入密碼 輸入兩次密碼後 產生密碼到指定的位置)

sudo sh -c "openssl passwd -apr1 >> /etc/apache2/.htpasswd"

 

第二種方式 透過htpasswd來產生

首先要安裝apache2-utils才能使用htpasswd

sudo apt-get install apache2-utils

接著輸入以下指令產生htpasswd (其中/etc/apache2/.htpasswd為檔案產生位置 username001為使用者名稱)

sudo htpasswd -c /etc/apache2/.htpasswd username001

接著會提示需要輸入密碼 輸入兩次密碼後 會把檔案產生到指定的位置

假如要新增其他使用者則是輸入以下指令(為前面的指令去掉-c)

sudo htpasswd /etc/apache2/.htpasswd username002

 

步驟二、設定Apache來加上密碼驗證

接下來要修改Apache virtual host設定檔 預設Apache virtual host設定檔位置在/etc/apache2/sites-enabled/000-default.conf 輸入指令
(如果設定檔位置不在這 請自行調整)

sudo nano /etc/apache2/sites-enabled/000-default.conf

然後需要在的Block中加上 以下內容(其中/var/www/html為程式碼放置位置 可以自行修改)
而AuthName為顯示需要登入時會顯示的訊息

<Directory "/var/www/html">
AuthType Basic
AuthName "You need to login"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
</Directory>

接著存檔後輸入指令重新啟動Apache伺服器

sudo service apache2 restart

這時候輸入網址會提示需要登入

假如驗證失敗會顯示401錯誤

另外也能不設定在Apache virtual host中 而是設定在.htaccess檔案中
但是要先設定啟動.htaccess (預設未開啟) 輸入以下指令修改apache設定

sudo nano /etc/apache2/apache2.conf

然後找到

Options Indexes FollowSymLinks
AllowOverride None
Require all granted

把AllowOverrider Node改成AllowOverrider All

Options Indexes FollowSymLinks
AllowOverride All
Require all granted

接著只需要到想要加上密碼驗證的資料夾 內加上.htaccess檔案
檔案內容加上

AuthType Basic
AuthName "You need to login"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user

這樣就完成了密碼驗證的設定了

然後重新啟動apache伺服器

sudo service apache2 restart

而假如只有特殊Url需要登入驗證的話 可以在.htaccess檔案中改成輸入

SetEnvIf Request_URI ^/specify/url require_auth=true
AuthUserFile /etc/apache2/.htpasswd
AuthName "Password Protected"
AuthType Basic

Order Deny,Allow
Deny from all
Satisfy any
Require valid-user
Allow from env=!require_auth

以這個例子來說 只要開頭是/specify/url的皆需要登入才能夠使用

2 thoughts on “[教學]對網頁啟用密碼驗證 (Apache)

辛比 發表迴響 取消回覆