Nginx自动化部署脚本(在线离线均适用)

时间:2023-01-20 08:53:47

#!/bin/bash
#********************************************************************
#Author: Wang Dajiang
#Date: 2023-01-18
#FileName: install_nginx.sh
#csdn: https://blog.csdn.net/sinat_41836475?type=blog
#********************************************************************
. /etc/os-release

version=1.22.0

function red(){
echo -e “\e[1;31m $1 \e[0m”
}

function gre(){
echo -e “\e[1;32m $1 \e[0m”
}

function nginx-file () {
echo -e “="
red “*【1.检查nginx源码包】
echo -e "
=”
if [ -e nginx- v e r s i o n . t a r . g z ] ; t h e n g r e " 文件已存在,安装进行中。。。 " e l s e g r e " 开始下载源码文件。。。 " w g e t h t t p : / / n g i n x . o r g / d o w n l o a d / n g i n x − {version}.tar.gz ];then gre "文件已存在,安装进行中。。。" else gre "开始下载源码文件。。。" wget http://nginx.org/download/nginx- version.tar.gz];thengre"文件已存在,安装进行中。。。"elsegre"开始下载源码文件。。。"wgethttp://nginx.org/download/nginx{version}.tar.gz
[ $? -eq 0 ] || { red “下载失败!立即退出!”;exit; }
fi
}

function nginx-user () {
echo -e “="
red “*******************【2.检查nginx用户】********************”
echo -e "
=”
if id nginx &> /dev/null;then
gre “nginx用户已存在。”
else
useradd -r -s /sbin/nologin -M nginx
gre “创建nginx用户。”
fi
}

function dependent-package () {
echo -e “="
red “*【3.检查nginx依赖包】
echo -e "
=”
if [ $ID == “rocky” -o $ID == “centos” ];then
yum -y install make gcc gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed
else
apt update &> /dev/null
apt -y install make gcc libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev &> /dev/null
fi
}

function nginx-install () {
echo -e “="
red “*******************【4.编译安装Nginx】********************”
echo -e "
=”
tar -xvf nginx-KaTeX parse error: Expected 'EOF', got '&' at position 36: …/usr/local/src &̲> /dev/null …{version}
./configure --prefix=/usr/local/nginx
–user=nginx
–group=nginx
–with-http_ssl_module
–with-http_v2_module
–with-http_realip_module
–with-http_stub_status_module
–with-http_gzip_static_module
–with-pcre
–with-stream
–with-stream_ssl_module
–with-stream_realip_module
make && make install
[ $? -eq 0 ] && gre "nginx-configure successed " || { echo “nginx-configure failed”;exit; }
chown -R nginx:nginx /usr/local/nginx
ln -sv /usr/local/nginx/sbin/nginx /usr/sbin/nginx
}

function nginx-service () {
echo -e “="
red “【5.配置systemctl管理nginx服务】
echo -e "
=”
cat > /lib/systemd/system/nginx.service << EOF
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s restart
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now nginx &> /dev/null
[ $? -eq 0 ] && gre “nginx-start successed !!!” || { red “nginx-start failed !!!”;exit; }
}

nginx-file
nginx-user
dependent-package
nginx-install
nginx-service