說明:ngx_http_auth_basic_module模組實現讓訪問者只有輸入正確的使用者密碼才允許訪問網頁內容。網頁上的一些內容不想被其他人知道,但是又想讓部分人看到。nginx的http auth模組以及Apache http auth都是很好的解決方案。

這裡以軍哥的LNMP為例,預設情況下nginx已經安裝了ngx_http_auth_basic_module模組。
Nginx 認證配置實例#
1、生成認證檔案
# printf "test:$(openssl passwd -crypt 123456)\n" >>/home/htpasswd
# cat /home/htpasswd
test:xyJkVhXGAZ8tM
** 注意:** 這裡帳號:test,密碼:123456,記住認證檔案路徑
2、配置網站 conf 檔案
server{
listen 80;
server_name www.moeyy.cn moeyy.cn;
index index.html index.php;
root /home/wwwroot/www.moeyy.cn;
location /
{
auth_basic "Please enter your username and password";
auth_basic_user_file /home/htpasswd;
autoindex on;
}
}
** 注意:** 一定要注意auth_basic_user_file路徑,否則會不厭其煩的出現 403。
3、重啟 Nginx
/etc/init.d/nginx restart
LNMP 下為 Nginx 目錄設置訪問驗證的使用者名稱密碼#
有時候需要像Apache那樣為指定的目錄添加訪問驗證,一般在Apache下使用htpasswd來添加,而htpasswd是包含在apache2-utils裡,一般LNMP一鍵安裝包或自己編譯安裝LNMP都不會安裝apache2-utils。
1、創建類 htpasswd 檔案
執行下面命令:
wget -c https://www.moeyy.cn/usr/down/htpasswd.sh;bash htpasswd.sh
按提示輸入使用者名稱、密碼、及認證檔案名。腳本會自動生成認證檔案。記錄下腳本返回的檔案路徑。如:/usr/local/nginx/conf/vpser.net.auth。
2、為 Nginx 添加 auth 認證配置
下面是以某域名下面的soft目錄為例,在域名的server段裡加上如下程式碼:
location ^~ /soft/
{
auth_basic "Authorized users only";
auth_basic_user_file 這裡寫前面腳本返回的檔案路徑;
}
Authorized users only為提示訊息,可以修改成自己想讓他提示的訊息;auth_basic_user_file後面需要填htpasswd.sh腳本返回的人家檔案的路徑。按上面的提示修改好配置後,重啟nginx,訪問http://yourdomainname/soft/ 就會提示輸入使用者名稱和密碼。
** 注意:** 加上認證之後該目錄下的PHP將不會被解析,會出現下載提示,如果想可以解析PHP可以將上面的配置改為:
location ^~ /soft/ {
location ~ .*\.(phpphp5)?$ {
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
auth_basic "Authorized users only";
auth_basic_user_file 這裡寫前面腳本返回的檔案路徑;
}
本教程適合 LNMP 一鍵安裝包或自己安裝的LNMP,只不過目錄和配置檔案可能位置不一樣。
設置完執行:/usr/local/nginx/sbin/nginx -t測試配置是否有錯誤。
再執行:/usr/local/nginx/sbin/nginx -s reload載入配置檔案。