比如要對 網站目錄下的 test 文件夾 進行加密認證
首先需要在opt 的主目錄中 /opt/ 創建一個新文件 htpasswd
此文件的書寫格式是
用戶名:密碼
每行一個賬戶
並且 密碼必須使用函數 crypt(3) 加密
官方檔說 可以用 Apache 的 htpasswd 工具來創建密碼文件
[root@localhost /]# htpasswd
-bash: htpasswd: command not found
[root@localhost /]#
如果上述提示則需要安裝httpd
yum install httpd
安裝好后執行如下命令
htpasswd -c /opt/nginxpwd user
New password:123456
Re-type new password:123456
Adding password for user ngin
生成用戶密鑰文件為nginxpwd 用戶名為user 密碼為123456
密碼文件生成好后,在 nginx.conf 文件中對應的 server 段中 添加如下內容
auth_basic "Welcome Back! GUOYU!";
auth_basic_user_file /opt/nginxpwd;
如果想限制某一個目錄的話需要如下配置:
location ^~ /test/ {
auth_basic "TEST-Login!";
auth_basic_user_file /opt/nginxpwd;
}
如果 不用 ^~ /test/ 而用 /test 的話 那么將只能對目錄進行驗證直接訪問其下的文件,將不會彈出登錄驗證
重啟Nginx服務,使配置生效
或者 ./nginx -s reload