The biggest feature of the Nginx Web server is that Nginx is often used for load balancing and reverse proxy. A single Nginx server is configured with multiple virtual hosts, and a hundred servers are configured with multiple virtual hosts. Based on Shell scripts, virtual hosts can be more efficiently configured and added ,management. This knowledge point mainly introduces the use of Shell scripts to implement automatic Nginx installation and maintenance of virtual hosts. The writing ideas are as follows:
- Determine whether the Nginx WEB software service is deployed or running;
- Support the addition of a single virtual host;
- Support adding multiple virtual hosts;
- Support deleting a single virtual host or multiple virtual hosts
Specific implementation script:
#!/bin/bash
#Mar 6, 2020 21:28:16
#auto config nginx vhosts
#by author lee
#########################
#Install nginx web
yum install -y wget gzip make tar gcc
yum install -y pcre pcre-devel zlib-devel
wget -c http://nginx.org/download/nginx-1.16.0.tar.gz
tar -xzf nginx-1.16.0.tar.gz
cd nginx-1.16.0
useradd -s /sbin/nologin www -M
./configure --prefix=/usr/local/nginx --user=www --group=www --with-http_stub_status_module
make
make install
/usr/local/nginx/sbin/nginx
ps -ef | grep nginx
netstat -tnlp|grep -w 80
setenforce 0
systemctl stop firewalld.service
#Config nginx vhosts
cd /usr/local/nginx/conf/
\cp nginx.conf nginx.conf.bak
grep -vE "#|^$" nginx.conf >nginx.conf.swp
sed -i '/server/,$d' nginx.conf.swp
echo -e " include vhosts/*;\n}" >>nginx.conf.swp
\cp nginx.conf.swp nginx.conf
mkdir -p vhosts
cd vhosts
cat>v1.jfedu.net<<EOF
server {
listen 80;
server_name v1.jfedu.net;
location / {
root html/v1.jfedu.net;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
EOF
mkdir -p /usr/local/nginx/html/v1.jfedu.net
cat>/usr/local/nginx/html/v1.jfedu.net/index.html<<EOF
<html>
<head>
<title><h1>v1.jfedu.net Test Pages.</h1></title>
</head>
<body>
<hr color=red>
</body>
</html>
EOF
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload