打zZ~瞌睡 Menu

Nginx中配置htpasswd

1. 下载生成htpasswd的脚本

#!/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:Licess http://www.lnmp.org #"
echo "====================================="

#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: /usr/local/nginx/conf/$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 /usr/local/nginx/conf/$htfile.conf ]; then
  echo "Create Auth file......"
cat >/usr/local/nginx/conf/$htfile.conf<<eof
$username:$password
eof
echo "Create Auth file successful,auth file path:/usr/local/nginx/conf/$htfile.conf."
else
	echo "File already exists,please run this script again."
	exit 1
由于编辑器限制,请自行将&gt;转为 >,将&lt;转化为 <

2. 设置脚本权限为可执行权限

chmod 0755 htpasswd.sh

3. 运行脚本生成密码文件
需要输入用户名、密码和文件名,脚本会帮我们生成好密码文件。

我的脚本是生成到/usr/local/nginx/conf目录下,如有需要,请在脚本中修改

4. 在Nginx虚拟站点的配置中加入以下两句

auth_basic "Authorized users only";
auth_basic_user_file /usr/local/nginx/conf/htpasswd.conf;
这里只是简单的验证,有权限即可。当然也可以改为只限制某个用户访问

5. 重启nginx生效

sudo /usr/local/nginx/sbin/nginx -s reload