nginx添加单个或多个虚拟主机(脚本)

添加单个或多个NGINX虚拟主机

#!/bin/bash
#auto create VHOST
#by author toyix
#20207421: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

猜你喜欢

转载自blog.csdn.net/oToyix/article/details/107131285