shell 编程实战Nginx 虚拟主机

NginxWeb服务器的最大特点在于Nginx常被用于负载均衡、反向代理,单台Nginx服务器配置多个虚拟主机,百台服务器配置N个虚拟主机,基于shell脚本可以更加高效地配置虚拟主机及添加、管理。
shell脚本实现Nginx自动安装及虚拟主机的维护:
脚本指定参数 www.wuyutang.com;
创建www.wuyutang.com同时创建目录/var/www/tang;
将Nginx虚拟主机配置定向到新的目录;
重复虚拟主机不再添加。
shell脚本实现Nginx自动安装及虚拟主机的配置:
#!/bin/bash
#Auto config Nginxvirtual Hosts
#By author tang.com2018
#Define Path variables
NGINX_CONF="/usr/local/nginx/conf"
NGINX_MAKE="--user=www--group=www --prefix=/usr/local/nginx --with-http_stub_status_module--with-http_ssl_module"
NGINX_SBIN="/usr/local/nginx/sbin/nginx"
NGINX_INSTALL(){
#Install Nginx server
NGINX_FILE=nginx-1.14.1.tar.gz
NGINX_DIR=`echo$NGINX_FILE |sed 's/.tar*.*//g'`
if [ ! -e/usr/local/nginx -a ! -e /etc/nginx ];then
pkillnginx
wget-c http://nginx.org/download/$NGINX_FILE
yuminstall pcre-devel pcre -y
rm-rf $NGINX_DIR;tar xf $NGINX_FILE
cd$NGINX_DIR;useradd www -s /usr/sbin/nologin -M;./configure $NGINX_MAKE
make&& make install
grep-vE "#|^$" $NGINX_CONF/nginx.conf > $NGINX_CONF/nginx.conf.swp
\mv$NGINX_CONF/nginx.conf.swp $NGINX_CONF/nginx.conf
fori in `seq 1 6`;do sed -i '$d' $NGINX_CONF/nginx.conf;done
echo"}" >> $NGINX_CONF/nginx.conf
cd../
fi
}
NGINX_CONFIG(){
#config tomcat nginxvhosts
grep "includedomains" $NGINX_CONF/nginx.conf >> /dev/null
if [ $? -ne 0 ];then
#sed-i '$d' $NGINX_CONF/nginx.conf
echo-e "\ninclude domains/*;\n}" >>$NGINX_CONF/nginx.conf
mkdir-p $NGINX_CONF/domains/
fi
VHOSTS=$1
ls$NGINX_CONF/domains/$VHOSTS>>/dev/null 2>&1
if [ $? -ne 0 ];then
#cp-r xxx.tang.com $NGINX_CONF/domains/$VHOSTS
#sed-i "s/xxx/$VHOSTS/g" $NGINX_CONF/domains/$VHOSTS
cat>$NGINX_CONF/domains/$VHOSTS<<EOF
#vhostsserver $VHOSTS
server{
listen        80;
server_name$VHOSTS;
location/ {
root/data/www/$VHOSTS/;
indexindex.html index.htm;
}
}                
EOF
mkdir -p /data/www/$VHOSTS
cat>/data/www/$VHOSTS/index.html<<EOF
<html>
<h1><center>TheFirst Test Nginx page.</center></h1>
<hrcolor="red">
<h2><center>$VHOSTS</center></h2>
</html>
EOF
echo-e "\033[32mThe $VHOSTS Config success,You can to access http://$VHOSTS/\033[0m"
NUM=`ps-ef |grep nginx|grep -v grep|grep -v auto|wc -l`
$NGINX_SBIN-t >>/dev/null 2>&1
if [$? -eq 0 -a $NUM -eq 0 ];then
$NGINX_CONF
else
$NGINX_SBIN-t >>/dev/null 2>&1
if [$? -eq 0 ];then
$NGINX_SBIN-s reload
fi
fi
else
echo-e "\033[32mThe $VHOSTS has been config,Please exit.\033[0m"
fi
}
if [ -z $1 ];then
echo-e "\033[32m----------------------------------------\033[0m"
echo-e "\033[32mPlease enter sh $0 xxx.tang.com.\033[0m"
exit0
fi
NGINX_INSTALL
NGINX_CONFIG $1