龚哥哥 爱生活、做自己!
Nginx支持htpasswd 访问需要用户和密码认证
发表于 2016-5-26 | 服务器

准备、创建脚本目录

/data/server/nginx/conf/htpasswd

一、创建文件 htpasswd.sh  内容如下

#!/bin/bash

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

echo "========================================"
echo "# A tool like htpasswd for Nginx       #"
echo "#--------------------------------------#"
echo "# Author:Devil http://gongfuxiang.com  #"
echo "========================================"

# file path
dir=$(pwd);
user="user.conf";
userfile="${dir}/${user}"

#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)

# create file
if [ ! -f ${userfile} ]; then
  touch ${userfile} 

  echo "Create Auth file......"
fi

# delete original user
for file in $userfile;
do         
    sed -i "/^$MON[\t ]*$username/d" $file  
done

# add user
echo $username:$password >> $userfile
if [ $? == 0 ]; then
    echo $username:$password;
    echo "user add success, Auth file  path:${userfile}."
else
        echo "error"
        exit 1
fi

二、修改虚拟机配置文件 server 中添加以下配置信息

auth_basic "Authorized users only";
auth_basic_user_file /data/server/nginx/conf/htpasswd/user.conf;

三、添加授权用户(根据提示输入用户名和密码)

sh htpasswd.sh

发表评论:

TOP