基于CentOS 7 编译安装Nginx 1.18

#! /bin/bash
# 编译安装nginx

# nginx版本
NGINX_version=nginx-1.18.0
# 下载网址
NGINX_Download_URL=http://nginx.org/download/${NGINX_version}.tar.gz

# nginx 安装路径
install_path=/apps/nginx

# nginx源码路径
SRC_DIR=/usr/local/src
# CPU数量
CPUS=`lscpu|grep "^CPU(s)"|awk '{print $2}'`
# 系统类型
os_type=`grep "^NAME" /etc/os-release |awk -F'"| ' '{print $2}'`
# 系统版本号
os_version=`awk -F'"' '/^VERSION_ID/{print $2}' /etc/os-release`

color (){
if [[ $2 -eq 0 ]];then
    echo -e "\e[1;32m$1\t\t\t\t\t\t[  OK  ]\e[0;m"
else
    echo $2
    echo -e "\e[1;31m$1\t\t\t\t\t\t[ FAILED ]\e[0;m"
fi
}

install_nginx () {
if [ -e ${NGINX_version}.tar.gz ];then
  color "${NGINX_version}.tar.gz 源码包已存在" 0
else
  color "开始下载源码包" 0
  wget ${NGINX_Download_URL}
fi
if [ $? -nq 0 ];then
  color "下载失败" 1
  exit 1
fi
color "开始安装 nginx" 0
if id nginx &>/dev/null;then
  color "nginx 用户已存在" 1
else
  useradd -s /sbin/nologin nginx
  color "创建nginx用户" 0
fi
color "开始安装nginx依赖包" 0
if [ ${os_type}=="CentOS" -a ${os_version}=="8" ];then
  yum -y install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed
elif [ ${os_type}=="CentOS" -a ${os_version}=="7" ];then
  yum -y install make gcc pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed
else
  color "系统不符,无法安装" 1
  exit 1
fi
tar -xvf ${NGINX_version}.tar.gz -C ${SRC_DIR}
cd ${SRC_DIR}
ln -s ${NGINX_version} nginx
cd nginx
./configure --prefix=${install_path} \
--user=nginx \
--group=nginx \
--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 \
--with-http_ssl_module
make -j ${CPUS} && make install
chown -R nginx:nginx /apps/nginx
ln -s ${install_path}/sbin/nginx /usr/sbin/nginx
cat > /usr/lib/systemd/system/nginx.service <<EOF
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=${install_path}/logs/nginx.pid
ExecStartPre=/bin/rm -f ${install_path}/logs/nginx.pid
ExecStartPre=${install_path}/sbin/nginx -t
ExecStart=${install_path}/sbin/nginx -c ${install_path}/conf/nginx.conf
ExecReload=/bin/kill -s HUP \$MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now nginx &>/dev/null
systemctl is-active nginx &>/dev/null
if [ $? -eq 0 ];then
  color "nginx已安装完成!" 0
else
  color "nginx 启动失败" 1
  exit 1
fi
}

install_nginx

exit 0
posted @ 2022-07-15 22:19  areke  阅读(129)  评论(0)    收藏  举报