添加單個或多個NGINX虛擬主機
#!/bin/bash
#auto create VHOST
#by author toyix
#2020年7月4日 21:36:26
##########################################
NGINX_BASE_DIR="/usr/local/nginx"
NGINX_VHOST_DIR="${NGINX_BASE_DIR}/conf/vhost"
if (( $# < 1 ));then
echo "請輸入要添加的域名,如,bbs.yjy.com。"
exit 1
fi
#判斷虛擬主機配置目錄vhost是否存在,如果不存在則創建目錄
if [ ! -d ${NGINX_VHOST_DIR} ];then
mkdir -p ${NGINX_VHOST_DIR}
fi
#配置nginx.conf文件
sed -i "26c include ${NGINX_VHOST_DIR}/*.conf;" ${NGINX_BASE_DIR}/conf/nginx.conf
sed -i "21,25 s/#//g" ${NGINX_BASE_DIR}/conf/nginx.conf
echo "測試並重啓nginx"
${NGINX_BASE_DIR}/sbin/nginx -t
${NGINX_BASE_DIR}/sbin/nginx -s reload
for DOMAIN_NAME in $*
do
echo "檢查虛擬主機項目目錄,有則跳過,沒有則創建"
if [ -e ${NGINX_VHOST_DIR}/${DOMAIN_NAME}.conf ];then
echo "虛擬主機DOMAIN_NAME已存在,請檢查目錄${NGINX_VHOST_DIR}"
else
echo "server{
listen 80;
server_name ${DOMAIN_NAME};
location / {
root ${NGINX_BASE_DIR}/html/${DOMAIN_NAME};
index index.html;
}
}">${NGINX_VHOST_DIR}/${DOMAIN_NAME}.conf
${NGINX_BASE_DIR}/sbin/nginx -s reload
echo "虛擬主機配置文件${NGINX_VHOST_DIR}/${DOMAIN_NAME}.conf已創建"
fi
if [ ! -d ${NGINX_BASE_DIR}/html/${DOMAIN_NAME} ];then
mkdir -p ${NGINX_BASE_DIR}/html/${DOMAIN_NAME}
echo "${DOMAIN_NAME}" >${NGINX_BASE_DIR}/html/${DOMAIN_NAME}/index.html
echo "創建了${DOMAIN_NAME}項目目錄及首頁index.html"
else
echo "${DOMAIN_NAME}項目目錄已存在,跳過創建項目目錄及文件"
fi
done
ls ${NGINX_VHOST_DIR}
ls ${NGINX_BASE_DIR}/html
執行結果
[root@localhost src]# ./auto_createNginx_Vhost.sh www.yjy.com bbs.yjy.com
測試並重啓nginx
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
檢查虛擬主機項目目錄,有則跳過,沒有則創建
虛擬主機配置文件/usr/local/nginx/conf/vhost/www.yjy.com.conf已創建
創建了www.yjy.com項目目錄及首頁index.html
檢查虛擬主機項目目錄,有則跳過,沒有則創建
虛擬主機配置文件/usr/local/nginx/conf/vhost/bbs.yjy.com.conf已創建
創建了bbs.yjy.com項目目錄及首頁index.html
bbs.yjy.com.conf www.yjy.com.conf
50x.html bbs.yjy.com index.html test.php www.yjy.com
[root@localhost src]#
[root@localhost src]#
[root@localhost src]# ls /usr/local/nginx/html/
50x.html bbs.yjy.com index.html test.php www.yjy.com
[root@localhost src]# ls /usr/local/nginx/conf/vhost/
bbs.yjy.com.conf www.yjy.com.conf
------------------------end