直接上干货,本脚本适用于centos7,centos8,rocky8.5 以及ubuntu20.04 版本linux。
ps
#该脚本的nginx的用户为www,版本为nginx1.20.2,nginx的安装目录为/apps/nginx
安装脚本
#!/bin/bash
#
#********************************************************************
#Author: lxp
#QQ: 17xxxxxx4
#FileName: install_nginx.sh
#Description: The test script
#Copyright (C): 2022 All rights reserved
#********************************************************************
NGINX_FILE=nginx-1.20.2
NGINX_INSTALL_DIR=/apps/nginx
NGINX_URL=http://nginx.org/download/
TAR=.tar.gz
SRC_DIR=/usr/local/src
CPUS=`lscpu | awk '/^CPU\(s)/{print $2}'`
. /etc/os-release
color () {
RES_COL=60
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \E[0m"
echo -n "$1" && $MOVE_TO_COL
echo -n "["
if [ $2 = "success" -o $2 = "0" ] ;then
${SETCOLOR_SUCCESS}
echo -n $" OK "
elif [ $2 = "failure" -o $2 = "1" ] ;then
${SETCOLOR_FAILURE}
echo -n $"FAILED"
else
${SETCOLOR_WARNING}
echo -n $"WARNING"
fi
${SETCOLOR_NORMAL}
echo -n "]"
echo
}
check () {
[ -e ${NGINX_INSTALL_DIR} ] && { color "nginx 已安装" 1 ; exit; }
cd ${SRC_DIR}
if [ -e ${NGINX_FILE}${TAR} ];then
color "相关文件已准备好" 0
exit
else
color '开始下载 nginx 源码包' 0
wget ${NGINX_URL}${NGINX_FILE}${TAR}
[ $? -ne 0 ] && { color "下载 ${NGINX_FILE}${TAR}文件失败" 1;exit; }
fi
}
install_nginx() {
color "install_nginx " 0
if id www &> /dev/null;then
color "nginx 用户已存在" 1
else
groupadd -g 88 www;useradd -u 88 -g www -s /sbin/nologin -r www
color "创建nginx组和用户" 0
fi
color "开始安装依赖" 0
if [ $ID == "centos" ] ; then
if [[ $VERSION_ID =~ ^7 ]]; then
yum -y -q install make gcc pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed
elif [[ $VERSION_ID =~ ^8 ]]; then
yum -y -q install make gcc-c++ libtool pcre pcre-devel zlib openssl openssl-devel zlib-devel perl-ExtUtils-Embed
else
color '不支持此系统' 1
exit
fi
elif [ $ID = "rocky" ];then
yum -y -q install make 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 pcre pcre-devel openssl openssl-devel libssl-dev zliblg-dev &> /dev/null
fi
tar xf ${NGINX_FILE}${TAR} -C $SRC_DIR
cd $SRC_DIR
NGINX_DIR=`echo ${NGINX_FILE}${TAR} | sed -nr 's/^(.*[0-9]).*/\1/p'`
cd ${NGINX_DIR}
./configure --prefix=${NGINX_INSTALL_DIR} --user=www --group=www --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 -j $CPU && make install
if [ $? -ne 0 ];then
echo Install nginx is failed!
exit 10
else
echo "Install nginx is finished!"
fi
echo "PATH=${NGINX_INSTALL_DIR}/sbin:${PATH}" > /etc/profile.d/nginx.sh
source /etc/profile.d/nginx.sh
mkdir ${NGINX_INSTALL_DIR}/conf/conf.d
chown -R nginx:nginx ${NGINX_INSTALL_DIR}
cat &g