nginx認證模塊ngx_http_auth_basic_module

ngx_http_auth_basic_module模塊基於“HTTP Basic Authentication“協議完成用戶認證。

模塊指令:

 auth_basic 

 auth_basic_user_file

這兩個指令的應用範圍:httpserverlocationlimit_except

 

示例:

 

location / {

    auth_basic           "closedsite";

    auth_basic_user_fileconf/htpasswd;

}

auth_basic指令:

 語法:auth_basic string | off;

 默認:auth_basic off;

開啓/關閉基於“HTTP Basic Authentication”協議的用戶/密碼認證。

 

auth_basic_user_file指令:

 語法:auth_basic_user_file file;

 默認:--

用於指定保存用戶名和密碼的文件,注意文件權限,chmod 400 file。

文件格式爲:

name1:password1

name2:password2:comment

name3:password3

支持的密碼類型:

  • 用crypt()函數加密,工具有htpasswd、openssl passwd

  • 使用基於md5的密碼算法的Apache變體(apr1)

 

使用htpasswd實現nginx的認證

  1. 安裝htpasswd,htpasswd是apache提供的密碼生成工具  

 yuminstall httpd-tools -y

 

 

  1. htpasswd用法

$ htpasswd -h

htpasswd:illegal option -- h

Usage:

    htpasswd[-cimBdpsDv] [-C cost] passwordfile username

    htpasswd-b[cmBdpsDv] [-C cost] passwordfile username password

    htpasswd-n[imBdps] [-C cost] username

    htpasswd-nb[mBdps] [-C cost] username password

-c  Createa new file.

-n  Don'tupdate file; display results on stdout.

-b  Usethe password from the command line rather than prompting for it.

-i  Readpassword from stdin without verification (for script usage).

-m  ForceMD5 encryption of the password (default).

-B  Forcebcrypt encryption of the password (very secure).

-C  Setthe computing time used for the bcrypt algorithm

     (higheris more secure but slower, default: 5, valid: 4 to 31).

-d  ForceCRYPT encryption of the password (8 chars max, insecure).

-s  ForceSHA encryption of the password (insecure).

-p  Donot encrypt the password (plaintext, insecure).

-D  Deletethe specified user.

-v  Verifypassword for the specified user.

 

 

  1. 創建用戶密碼文件

[roger@test ~]$ htpasswd -c/etc/nginx/passwd.db xiaoming ###新創建密碼文件

New password:

Re-type new password:

Adding password for user xiaoming

[roger@test ~]$ htpasswd/etc/nginx/passwd.db xiaoli ###添加新的用戶

New password:

Re-type new password:

Adding password for user xiaoli

[roger@test ~]$ cat/etc/nginx/passwd.db        ###查看文件內容格式

xiaoming:$apr1$OlmGwtmd$kG6fmWrQzCWEJGT/uWXsJ.

xiaoli:$apr1$UNkIjCHM$5h6Gigl1q.IZbq6yODzAv1


 

 

  1. 配置nginx

location / {

    auth_basic           "welcome";

    auth_basic_user_file /etc/nginx/passwd.db;

}

  1. 訪問相關內容的時候將會認證

    wKiom1nl1oSDZw2SAAAZ63BET1Y888.png

    使用對應的用戶名密碼可以登錄訪問。

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章