NGINX为目录增加密码保护

2012年 16月 03日 02:52
为了防止一些可能出现存在漏洞的后台脚本暴露,使用验证的方式保护这些文件所在的目录 使用apache的htpasswd工具生成密码
[email protected]:~$ htpasswd -b -c filename username passwd
Adding password for user ******

命令参数注释: 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 使用命令行处理 -c创建密码 后面3个参数分别是 文件名,用户名 密码 附一个可用的bash脚本 用于创建密码
   #!/bin/bash
   PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
   export PATH

   #set UserName

           username=""
           read -p "Please input UserName:" username
           if [ "$username" = "" ]; then
                   echo "Error:UserName can't be NULL!"
                   exit 1
           fi
           echo "==========================="
           echo "UserName was: $username"
           echo "==========================="

   #set password

           unpassword=""
           read -p "Please input the Password:" unpassword
           if [ "$unpassword" = "" ]; then
                   echo "Error:Password can't be NULL!"
                   exit 1
           fi
           echo "==========================="
           echo "Password was: $unpassword"
           echo "==========================="
   password=$(perl -e 'print crypt($ARGV[0], "pwdsalt")' $unpassword)

   #set htpasswd file

           htfile=""
           read -p "Please input Auth filename:" htfile
           if [ "$htfile" = "" ]; then
                   echo "Error:Auth filename can't be NULL!"
                   exit 1
           fi
           echo "==========================="
           echo "Auth File:$htfile"
           echo "==========================="

           get_char()
           {
           SAVEDSTTY=`stty -g`
           stty -echo
           stty cbreak
           dd if=/dev/tty bs=1 count=1 2> /dev/null
           stty -raw
           stty echo
           stty $SAVEDSTTY
           }
           echo ""
           echo "Press any key to Creat...or Press Ctrl+c to cancel"
           char=`get_char`
   if [ ! -f $htfile ]; then
     echo "Create Auth file......"
cat >$htfile<

加执行权限后 跟据操作提示
输入用于名,密码 文件路径即可,
由于我放的目录不在NGINX目录.稍稍修改了下.. 可用

然后修改 NGINX配置
需要注意的是目录
.*是此目录的所有文件
否则 导致  可直接访问 admin/index.php

PHP 需要重新解释 

location ~^/admin/.* {
    auth_basic "sorry ,for admin";
    auth_basic_user_file /usr/passwd/yxmiandroid.pwd;
location ~ .php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /www/$fastcgi_script_name;
include fastcgi_params;

}

}

tags: