摘要:Nginx開(kāi)啟使用“HTTP基本認(rèn)證”(HTTP Basic Authentication)協(xié)議的用戶名密碼驗(yàn)證,指定的參數(shù)被用作域,auth_basic配置示例: location / { auth_basic "Authorization"; auth_basic_user_file /etc/nginx/conf/htpasswd; }
auth_basic配置示例:
location / { auth_basic "Authorization"; auth_basic_user_file /etc/nginx/conf/htpasswd; }
Nginx開(kāi)啟使用“HTTP基本認(rèn)證”(HTTP Basic Authentication)協(xié)議的用戶名密碼驗(yàn)證。指定的參數(shù)被用作域。參數(shù)可以包含變量(1.3.10,1.2.7)。參數(shù)off可以取消繼承自上一個(gè)配置等級(jí)auth_basic指令的影響。參數(shù)off表示不開(kāi)啟HTTP基本認(rèn)證,另外auth_basic指定的字符串會(huì)在彈窗中顯示。
auth_basic_user_file
語(yǔ)法: auth_basic_user_file file;
默認(rèn)值: —
上下文: http,server,location,limit_except
指定保存用戶名密碼的文件,格式如下:
name1:password1 name2:password2:comment name3:password3 #用戶名:密碼:注釋
參數(shù)file中可以包含變量。
密碼應(yīng)該使用crypt()函數(shù)加密。可以用Apache HTTP Server發(fā)行包中的htpasswd命令或者openssl passwd來(lái)創(chuàng)建此類文件。
參數(shù)file可以是文件、相對(duì)路徑的文件、絕對(duì)路徑的文件。非絕對(duì)路徑下,文件的位置是相對(duì)于nginx安裝路徑下的conf目錄的。比如nginx的安裝路徑是/usr/local/nginx,則設(shè)置對(duì)應(yīng)的路徑舉例說(shuō)明如下:
auth_basic_user_file htpasswd; # htpasswd在機(jī)器上的位置:/usr/local/nginx/conf/htpasswd auth_basic_user_file conf/htpasswd; # htpasswd在機(jī)器上的位置:/usr/local/nginx/conf/conf/htpasswd auth_basic_user_file /tmp/htpasswd; # htpasswd在機(jī)器上的位置:/tmp/htpasswd
創(chuàng)建用戶名為admin,密碼為123456的示例如下 (htpasswd文件名可任意修改):
echo -e "admin:$(openssl passwd -crypt 123456)" > htpasswd
nginx_http_auth_request_module 第三方認(rèn)證
編譯 Nginx 時(shí)需要添加該模塊 --with-http_auth_request_module
該模塊可以將客戶端輸入的用戶名、密碼 username:password 通過(guò) Base64 編碼后寫入 Request Headers 中,然后通過(guò)第三方程序解碼后跟數(shù)據(jù)庫(kù)中用戶名、密碼進(jìn)行比較,Nginx 服務(wù)器通過(guò) header 的返回狀態(tài)判斷是否認(rèn)證通過(guò)。
檢查是否安裝 nginx_http_auth_request_module 模塊:
nginx -V
編輯nginx配置文件
server { listen 80; server_name local.server.com; location / { # 啟用認(rèn)證 auth_request /auth; # 請(qǐng)求不是文件或路徑,則訪問(wèn)跟目錄下的/index.php try_files $uri $uri/ /index.php?$query_string; } location /auth { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Original-URI $request_uri; proxy_pass_request_body off; proxy_set_header Content-Length ""; # 認(rèn)證服務(wù)器地址 proxy_pass http://localhost:8080/HttpBasicAuthenticate.php; } }
PHP認(rèn)證程序
<?php if(isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])){ $username = $_SERVER['PHP_AUTH_USER']; $password = $_SERVER['PHP_AUTH_PW']; if ($username == 'admin' && $password == '123456'){ return true; } } header('WWW-Authenticate: Basic realm="Git Server"'); header('HTTP/1.0 401 Unauthorized');
重啟nginx
sudo nginx -t sudo nginx -s reload