nginx可以為網站或目錄甚至特定的文件設置密碼認證。密碼必須是crypt加密的??梢杂胊pache的htpasswd來創建密碼。
格式為:
htpasswd -b -c site_pass username password
site_pass為密碼文件。放在同nginx配置文件同一目錄下,當然你也可以放在其它目錄下,那在nginx的配置文件中就要寫明絕對地址或相對當前目錄的地址。
如果你輸入htpasswd命令提示沒有找到命令時,你需要安裝httpd。如果是centos可以執行如下來安裝,
yum install httpd
如果你不想安裝httpd的話,可以使用perl腳本來實現(代碼如下:)
#! /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; }為腳本賦予可執行權限:
chmod o+x add_user.pl
腳本使用方法:
./add_user.pluser:password
把生成的用戶名密碼粘貼到/usr/local/nginx/conf/vhost/nginx_passwd文件中即可
如果是為了給網站加上認證,可以直接將認證語句寫在nginx的配置server段中。
如果是為了給目錄加上認證,就需要寫成目錄形式了。同時,還要在目錄中加上php的執行,否則php就會被下載而不執行了。
例如:基于整個網站的認證,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文件不會執行并且會被下載。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; }
這里有一個細節,就是location ~ ^/admin/.* {…} 保護admin目錄下的所有文件。如果你只設了/admin/ 那么直接輸入/admin/index.php還是可以訪問并且運行的。 ^/admin/.* 意為保護該目錄下所有文件。當然,只需要一次認證。并不會每次請求或每請求一個文件都要認證一下。
新聞熱點
疑難解答