shell指令碼一鍵安裝nginx-1.18.0

misakivv發表於2024-04-23

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 安裝完成。"

相關文章