shell脚本一键安装nginx-1.18.0

shell脚本一键安装nginx-1.18.0

#!/bin/bash

set -euo pipefail

NGINX_VERSION="1.18.0"
DOWNLOAD_URL="https://nginx.org/download/nginx-$NGINX_VERSION.tar.gz"
INSTALL_DIR="/apps/nginx"
PACKAGE_LIST="gcc pcre-devel openssl-devel zlib-devel"

echo "开始安装 Nginx $NGINX_VERSION..."
echo "1. 安装依赖包..."
if yum list installed $PACKAGE_LIST &> /dev/null; then
    echo "依赖包已安装。"
else
    echo "正在安装依赖包:$PACKAGE_LIST"
    yum -y install $PACKAGE_LIST > /dev/null
    echo "依赖包安装完成。"
fi

echo "2. 创建非登录用户 nginx..."
if id -u nginx &> /dev/null; then
    echo "用户 nginx 已存在。"
else
    useradd -r -s /sbin/nologin nginx > /dev/null
    echo "用户 nginx 创建完成。"
fi

echo "3. 下载并解压 Nginx 源码..."
if [[ -f "/usr/local/src/nginx-$NGINX_VERSION.tar.gz" ]]; then
    echo "Nginx 源码文件已存在,跳过下载。"
else
    wget -q -O "/usr/local/src/nginx-$NGINX_VERSION.tar.gz" "$DOWNLOAD_URL" > /dev/null
    echo "Nginx 源码下载完成。"
fi

cd /usr/local/src || exit 1
tar xzvf "nginx-$NGINX_VERSION.tar.gz" > /dev/null
echo "Nginx 源码解压完成。"

cd "nginx-$NGINX_VERSION" || exit 1

echo "4. 配置、编译及安装 Nginx..."
./configure --prefix="$INSTALL_DIR" \
           --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 > /dev/null

make -j 2 > /dev/null
make install > /dev/null

echo "Nginx 编译及安装完成。"

echo "5. 设置目录权限..."
chown -R nginx.nginx "$INSTALL_DIR" > /dev/null
echo "目录权限设置完成。"

echo "6. 创建符号链接..."
ln -s "$INSTALL_DIR/sbin/nginx" /usr/bin/ > /dev/null
echo "符号链接创建完成。"

echo "7. 创建并配置 systemd 服务文件..."
mkdir -p /apps/nginx/run/

cat > /usr/lib/systemd/system/nginx.service << EOF
[Unit]
Description=The nginx HTTP and reverse proxy server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/apps/nginx/run/nginx.pid
ExecStart=/apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP \$MAINPID
Execstop=/bin/kill -sTERM \$MAINPID

[Install]
WantedBy=multi-user.target
EOF

sed -i '/^#pid.*$/a pid        /apps/nginx/run/nginx.pid;' /apps/nginx/conf/nginx.conf > /dev/null

systemctl daemon-reload > /dev/null
systemctl enable --now nginx > /dev/null

echo "Nginx 服务已配置并启动。"

echo "Nginx 安装完成。"
posted @ 2024-04-23 23:22  misakivv  阅读(36)  评论(0编辑  收藏  举报