nginx可以為網(wǎng)站或目錄甚至特定的文件設(shè)置密碼認(rèn)證。密碼必須是crypt加密的。可以用apache的htpasswd來(lái)創(chuàng)建密碼。
格式為:
htpasswd -b -c site_pass username password
site_pass為密碼文件。放在同nginx配置文件同一目錄下,當(dāng)然你也可以放在其它目錄下,那在nginx的配置文件中就要寫(xiě)明絕對(duì)地址或相對(duì)當(dāng)前目錄的地址。
如果你輸入htpasswd命令提示沒(méi)有找到命令時(shí),你需要安裝httpd。如果是centos可以執(zhí)行如下來(lái)安裝,
yum install httpd
如果你不想安裝httpd的話,可以使用perl腳本來(lái)實(shí)現(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/nginx_passwd文件中即可
如果是為了給網(wǎng)站加上認(rèn)證,可以直接將認(rèn)證語(yǔ)句寫(xiě)在nginx的配置server段中。
如果是為了給目錄加上認(rèn)證,就需要寫(xiě)成目錄形式了。同時(shí),還要在目錄中加上php的執(zhí)行,否則php就會(huì)被下載而不執(zhí)行了。
例如:基于整個(gè)網(wǎng)站的認(rèn)證,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; }
針對(duì)目錄的認(rèn)證,在一個(gè)單獨(dú)的location中,并且在該location中嵌套一個(gè)解釋php的location,否則php文件不會(huì)執(zhí)行并且會(huì)被下載。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; }
這里有一個(gè)細(xì)節(jié),就是location ~ ^/admin/.* {…} 保護(hù)admin目錄下的所有文件。如果你只設(shè)了/admin/ 那么直接輸入/admin/index.php還是可以訪問(wèn)并且運(yùn)行的。 ^/admin/.* 意為保護(hù)該目錄下所有文件。當(dāng)然,只需要一次認(rèn)證。并不會(huì)每次請(qǐng)求或每請(qǐng)求一個(gè)文件都要認(rèn)證一下。
新聞熱點(diǎn)
疑難解答
圖片精選