溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Nginx服務(wù)器中為網(wǎng)站或目錄添加認證密碼的配置詳解

發(fā)布時間:2020-08-11 03:22:31 來源:ITPUB博客 閱讀:136 作者:慕容鈺靈 欄目:建站服務(wù)器

這篇文章主要介紹了Nginx服務(wù)器中為網(wǎng)站或目錄添加認證密碼的配置詳解,使用到了Apache的htpasswd工具,需要的朋友可以參考下

nginx可以為網(wǎng)站或目錄甚至特定的文件設(shè)置密碼認證。密碼必須是crypt加密的??梢杂胊pache的htpasswd來創(chuàng)建密碼。


格式為:


htpasswd -b -c site_pass username password

site_pass為密碼文件。放在同nginx配置文件同一目錄下,當(dāng)然你也可以放在其它目錄下,那在nginx的配置文件中就要寫明絕對地址或相對當(dāng)前目錄的地址。


如果你輸入htpasswd命令提示沒有找到命令時,你需要安裝httpd。如果是centos可以執(zhí)行如下來安裝,


yum install httpd

如果你不想安裝httpd的話,可以使用perl腳本來實現(xiàn)(代碼如下:)


#! /usr/bin/perl -w #filename: add_ftp_user.pl use strict; # print "#example: user:passwd\n"; while (<STDIN>) { exit if ($_ =~/^\n/); chomp; (my $user, my $pass) = split /:/, $_, 2; my $crypt = crypt $pass, '$1$' . gensalt(8); print "$user:$crypt\n"; } sub gensalt { my $count = shift; my @salt = ('.', '/', 0 .. 9, 'A' .. 'Z', 'a' .. 'z'); my $s; $s .= $salt[rand @salt] for (1 .. $count); return $s; }

為腳本賦予可執(zhí)行權(quán)限:

chmod o+x add_user.pl

腳本使用方法:


./add_user.pluser:password

把生成的用戶名密碼粘貼到/usr/local/nginx/conf/vhost/http://www.bbqmw.net/qm_yeqm//nginx_passwd文件中即可


如果是為了給網(wǎng)站加上認證,可以直接將認證語句寫在nginx的配置server段中。


如果是為了給目錄加上認證,就需要寫成目錄形式了。同時,還要在目錄中加上php的執(zhí)行,否則php就會被下載而不執(zhí)行了。


例如:基于整個網(wǎng)站的認證,auth_basic在php解釋之前。


server { listen 80; server_name www.iis7.com jb51.net; root /www/jb51.net; index index.html index.htm index.php; auth_basic "input you user name and password"; auth_basic_user_file /usr/local/nginx/conf/vhost/nginx_passwd; location ~ .php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; } location ~ /\.ht { deny all; } access_log /logs/jb51.net_access.log main; }

針對目錄的認證,在一個單獨的location中,并且在該location中嵌套一個解釋php的location,否則php文件不會執(zhí)行并且會被下載。auth_basic在嵌套的location之后。


server { listen 80; server_name www.iis7.com jb51.net; root /www/jb51.net; index index.html index.htm index.php; location ~ ^/admin/.* { location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; } auth_basic "auth"; auth_basic_user_file /usr/local/nginx/conf/vhost/auth/admin.pass; } location ~ .php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; } location ~ /\.ht { deny all; } access_log /logs/jb51.net_access.log main; }

這里有一個細節(jié),就是location ~ ^/admin/.* {…} 保護admin目錄下的所有文件。如果你只設(shè)了/admin/ 那么直接輸入/admin/index.php還是可以訪問并且運行的。 ^/admin/.* 意為保護該目錄下所有文件。當(dāng)然,只需要一次認證。并不會每次請求或每請求一個文件都要認證一下。


向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI