一.需求描述 Nginx作为web server的服务。因业务需要在访问网站时,加一层认证信息,以防止公司之外的人访问网站。需求类似于Apache那样为指定的目录添加访问验证,一般在Apache下使用htpasswd来添加。这里是为Nginx添加。
二.编写以下程序 环境:需要支持perl。(因为用到perl) vi htpasswd.sh
#!/bin/bash PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/binexport PATH echo "=====================================" echo "# A tool like htpasswd for Nginx #" echo "#-----------------------------------#" echo "# Author:Licess http://blog.csdn.net/longxibendi #" 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: /longxibendi/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 /longxibendi/nginx/conf/$htfile.conf ]; then make -p /longxibendi/nginx/conf/$htfile.conf echo "Create Auth file......" cat >/longxibendi/nginx/conf/$htfile.conf<<eof$username:$password eof echo "Create Auth file successful,auth file path:/longxibendi/nginx/conf/$htfile.conf." else echo "File already exists,please run this script again." exit 1 fi
三.生成用户名密码信息 bash htpasswd.sh 按提示输入用户名、密码、及认证文件名。脚本会自动生成认证文件。记录下脚本返回的文件路径。如:/longxibendi/nginx/conf/longxibendi.auth.conf
四.修改Nginx.conf配置文件,为Nginx添加auth认证配置
location ^~ /longxibendi/ 或者在location后面添加,比如
location / {
五.重启Nginx cd sbin/nginx ;./nginx -s reload
六.注意事项 每个浏览器初次访问,输入用户名、密码。只需要输入一次,之后再打开浏览器就不需要输入了。 (责任编辑:IT) |