首先使用Apache的htpasswd工具创建用户密码,密码必须是crypt加密

shell>> htpasswd -b -c filename username passwd
Adding password for user ******

filename即创建好的文件,把这个文件放在无法通过WEB路径访问的目录下,在Nginx配置文件中给出这个文件的绝对路径地址;如果是放在WEB目录下,最好命名为.ht****之类的文件名,并禁止下载

对整个网站的保护,直接将auth语句写在server段中,位于php解释语句之前

server { 
    listen       80; 
    server_name www.domain.com; 
    root  /htdocs/domain.com; 
    index index.html index.htm index.php; 
  
    auth_basic "Password Needed"; 
    auth_basic_user_file /etc/nginx/vhosts/auth/domain.passwd; 
  
    location ~ .php$ { 
        fastcgi_pass  127.0.0.1:9000; 
        fastcgi_index index.php; 
        include fastcgi_params; 
    } 
    location ~ /.ht { 
         deny  all; 
    } 
}

对单个目录的保护,auth语句写在单独的location的后端,如果被保护的目录需要php支持,那么这个location中还需单独写入php解释语句(位于auth语句之前),

server { 
    listen       80; 
    server_name www.domain.com; 
    root  /htdocs/domain.com; 
    index index.html index.htm index.php; 
  
    location ~ ^/authdir/.* { 
        location ~ .php$ { 
            fastcgi_pass  127.0.0.1:9000; 
            fastcgi_index index.php; 
            include fastcgi_params; 
        } 
  
        auth_basic "Password Needed"; 
        auth_basic_user_file /etc/nginx/vhosts/auth/domain.passwd; 
    } 
  
    location ~ .php$ { 
        fastcgi_pass  127.0.0.1:9000; 
        fastcgi_index index.php; 
        include fastcgi_params; 
    } 
  
    location ~ /.ht { 
         deny  all; 
    } 
}

注意:location ~ ^/authdir/.* {…} 保护authdir目录下的所有文件。如果写作/authdirn/, 那么直接输入/autdir/filename.php仍然可以访问并运行,这就失去了保护整个目录的本意, ^/authdir/.* 则可以保护该目录下所有文件。

附:htpasswd参数
命令参数注释:

Usage:
htpasswd [-cmdpsD] passwordfile username
htpasswd -b[cmdpsD] passwordfile username password
htpasswd -n[mdps] username
htpasswd -nb[mdps] username password
-c Create a new file.
-n Don’t update file; display results on stdout.
-m Force MD5 encryption of the password (default).
-d Force CRYPT encryption of the password.
-p Do not encrypt the password (plaintext).
-s Force SHA encryption of the password.
-b Use the password from the command line rather than prompting for it.
-D Delete the specified user.
-b 使用命令行处理