Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

CentOS 一鍵安裝 Nginx 腳本實戰:依賴、編譯、配置與服務註冊全自動化

編輯:Linux 教學

針對僅需 Nginx 靜態 Web/反向代理場景,避開 LNMP 全套編譯的漫長等待,本文提供一個精簡、可定製的一鍵安裝腳本,涵蓋依賴安裝、PCRE 靜態編譯、Nginx 模組裁剪、配置文件部署、防火牆放行與 SystemV 服務註冊。

腳本設計原則

  • 最小依賴:僅安裝編譯必需的開發庫,運行時依賴由系統包管理器解決。
  • 版本鎖定:指定 PCRE 8.36、Nginx 1.6.2(可按需升級),避免上游變更導致構建失敗。
  • 安全預設:以 nobody:nobody 低權限用戶運行,禁用不必要的模組。
  • 冪等性:重複執行不產生副作用(目錄存在性檢查、配置備份)。

核心腳本內容(nginx-install.sh)

#!/bin/bash
set -euo pipefail

# === 可配置變量 ===
NGINX_VER="1.24.0"          # 建議升級至最新穩定版
PCRE_VER="8.45"
INSTALL_PREFIX="/usr/local/nginx"
RUN_USER="nobody"
RUN_GROUP="nobody"
WWW_ROOT="/home/wwwroot/default"
WWW_LOGS="/home/wwwlogs"

# === 1. 安裝編譯依賴 ===
echo "[1/6] 安裝編譯依賴..."
yum install -y gcc gcc-c++ make automake autoconf libtool \
    pcre-devel zlib-devel openssl-devel wget tar gzip

# === 2. 下載並編譯 PCRE (靜態鏈接) ===
echo "[2/6] 編譯 PCRE $PCRE_VER..."
cd /tmp
wget -q "https://sourceforge.net/projects/pcre/files/pcre/${PCRE_VER}/pcre-${PCRE_VER}.tar.gz"
tar xzf "pcre-${PCRE_VER}.tar.gz"
cd "pcre-${PCRE_VER}"
./configure --prefix=/usr/local/pcre --enable-utf8 --enable-unicode-properties
make -j"$(nproc)" && make install
cd ..

# === 3. 下載並編譯 Nginx ===
echo "[3/6] 編譯 Nginx $NGINX_VER..."
wget -q "https://nginx.org/download/nginx-${NGINX_VER}.tar.gz"
tar xzf "nginx-${NGINX_VER}.tar.gz"
cd "nginx-${NGINX_VER}"

./configure \
    --prefix="${INSTALL_PREFIX}" \
    --user="${RUN_USER}" --group="${RUN_GROUP}" \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_realip_module \
    --with-http_stub_status_module \
    --with-http_gzip_static_module \
    --with-http_sub_module \
    --with-pcre=/tmp/pcre-${PCRE_VER} \
    --with-pcre-jit \
    --with-threads \
    --with-file-aio \
    --with-http_slice_module \
    --with-stream \
    --with-stream_ssl_module \
    --with-stream_realip_module

make -j"$(nproc)" && make install

# === 4. 部署配置文件與目錄結構 ===
echo "[4/6] 部署配置與目錄..."
mkdir -p "${WWW_ROOT}" "${WWW_LOGS}"
chown -R "${RUN_USER}:${RUN_GROUP}" "${WWW_ROOT}" "${WWW_LOGS}"
chmod 755 "${WWW_ROOT}" "${WWW_LOGS}"

# 備份原配置
[ -f "${INSTALL_PREFIX}/conf/nginx.conf" ] && \
    mv "${INSTALL_PREFIX}/conf/nginx.conf" "${INSTALL_PREFIX}/conf/nginx.conf.bak.$(date +%s)"

# 寫入生產級預設配置 (可替換為 wget 遠程拉取)
cat > "${INSTALL_PREFIX}/conf/nginx.conf" <<'EOF'
user nobody nobody;
worker_processes auto;
error_log /home/wwwlogs/error.log warn;
pid /var/run/nginx.pid;
worker_rlimit_nofile 65535;

events {
    use epoll;
    worker_connections 65535;
    multi_accept on;
}

http {
    include mime.types;
    default_type application/octet-stream;
    charset utf-8;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
    access_log /home/wwwlogs/access.log main;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    client_max_body_size 100m;

    gzip on;
    gzip_vary on;
    gzip_min_length 1k;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    server {
        listen 80;
        server_name _;
        root /home/wwwroot/default;
        index index.html index.htm;

        location / {
            try_files $uri $uri/ =404;
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html { root html; }
    }
}
EOF

# === 5. 註冊 SystemV 服務並配置開機自啟 ===
echo "[5/6] 註冊服務..."
cat > /etc/init.d/nginx <<'EOF'
#!/bin/bash
# nginx SysV init script
NGINX="/usr/local/nginx/sbin/nginx"
CONF="/usr/local/nginx/conf/nginx.conf"
PID="/var/run/nginx.pid"
NAME="nginx"
DESC="nginx daemon"

test -x $NGINX || exit 0

start() {
    echo -n "Starting $DESC: "
    $NGINX -c $CONF
    echo "$NAME."
}

stop() {
    echo -n "Stopping $DESC: "
    $NGINX -c $CONF -s quit
    echo "$NAME."
}

reload() {
    echo -n "Reloading $DESC: "
    $NGINX -c $CONF -s reload
    echo "$NAME."
}

case "$1" in
    start) start ;;
    stop) stop ;;
    restart) stop; sleep 1; start ;;
    reload) reload ;;
    *) echo "Usage: $0 {start|stop|restart|reload}"; exit 1 ;;
esac
exit 0
EOF
chmod +x /etc/init.d/nginx
chkconfig --add nginx
chkconfig --level 345 nginx on

# === 6. 防火牆放行 80/443 埠 ===
echo "[6/6] 配置防火牆..."
if command -v firewall-cmd &>/dev/null; then
    firewall-cmd --permanent --add-service=http
    firewall-cmd --permanent --add-service=https
    firewall-cmd --reload
elif command -v iptables &>/dev/null; then
    iptables -I INPUT -p tcp --dport 80 -j ACCEPT
    iptables -I INPUT -p tcp --dport 443 -j ACCEPT
    service iptables save
fi

# === 完成 ===
ldconfig
ln -sf "${INSTALL_PREFIX}/sbin/nginx" /usr/sbin/nginx
echo "=================================================="
echo "Nginx $NGINX_VER 安裝完成!"
echo "安裝路徑: ${INSTALL_PREFIX}"
echo "配置文件: ${INSTALL_PREFIX}/conf/nginx.conf"
echo "網站根目錄: ${WWW_ROOT}"
echo "日誌目錄: ${WWW_LOGS}"
echo "管理命令: service nginx {start|stop|restart|reload}"
echo "版本檢查: nginx -V"
echo "=================================================="

使用方法

chmod +x nginx-install.sh
sudo ./nginx-install.sh
# 安裝完成後驗證
nginx -V
curl -I https://localhost

進階定製建議

  • 模組裁剪:根據業務刪減 --with-http_* 模組,減小二進制體積、縮小攻擊面。
  • TLS 優化:啟用 --with-http_v2_module、--with-openssl=../openssl-1.1.1 靜態鏈接新版 OpenSSL 支援 TLS 1.3、ChaCha20-Poly1305。
  • 第三方模組:加入 --add-module=../ngx_brotli、--add-module=../nginx-http-flv-module 等。
  • systemd 服務:CentOS 7+ 建議改寫為 /usr/lib/systemd/system/nginx.service,支援 systemctl 管理。
Copyright © Windows教程網 All Rights Reserved