Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

CentOS 7/8 從源碼編譯安裝 Nginx 完整教程

編輯:Linux 系統常見問題解答

依賴環境準備


# 1. 安裝編譯工具鏈
yum install -y gcc gcc-c++ make automake

# 2. 安裝 PCRE (正則重寫模塊依賴)
yum install -y pcre pcre-devel
# 或源碼安裝指定版本
# wget https://sourceforge.net/projects/pcre/files/pcre/8.45/pcre-8.45.tar.gz
# tar xf pcre-8.45.tar.gz && cd pcre-8.45 && ./configure --enable-utf8 && make && make install

# 3. 安裝 OpenSSL (HTTPS 支持)
yum install -y openssl openssl-devel
# 或源碼安裝
# wget https://www.openssl.org/source/openssl-1.1.1w.tar.gz
# tar xf openssl-1.1.1w.tar.gz && cd openssl-1.1.1w && ./config && make && make install

# 4. 安裝 zlib (gzip 壓縮)
yum install -y zlib zlib-devel

下載並編譯 Nginx


# 1. 獲取源碼 (穩定版)
wget https://nginx.org/download/nginx-1.24.0.tar.gz
tar xf nginx-1.24.0.tar.gz
cd nginx-1.24.0

# 2. 配置編譯選項
./configure \
    --prefix=/usr/local/nginx \
    --with-pcre=/usr/local/src/pcre-8.45 \      # 若源碼安裝 PCRE 指定路徑,yum 安裝可省略
    --with-openssl=/usr/local/src/openssl-1.1.1w \ # 同理
    --with-zlib=/usr/local/src/zlib-1.2.13 \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_realip_module \
    --with-http_stub_status_module \
    --with-http_gzip_static_module \
    --with-threads \
    --with-file-aio \
    --user=nginx \
    --group=nginx

# 3. 編譯安裝
make -j$(nproc)
make install

創建系統用戶與 systemd 服務


# 1. 用戶/組
useradd -r -s /sbin/nologin -M nginx

# 2. systemd 服務文件 /usr/lib/systemd/system/nginx.service
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

啟動與驗證


systemctl daemon-reload
systemctl enable --now nginx
systemctl status nginx
curl -I 127.0.0.1

常用操作

操作命令
測試配置/usr/local/nginx/sbin/nginx -t
平滑重載/usr/local/nginx/sbin/nginx -s reload
停止/usr/local/nginx/sbin/nginx -s quit
查看版本/模塊/usr/local/nginx/sbin/nginx -V

目錄結構說明

/usr/local/nginx/
├── conf/           # 配置文件 (nginx.conf)
├── logs/           # access.log, error.log, nginx.pid
├── sbin/           # nginx 二進制
└── html/           # 默認靜態頁面

升級/遷移建議

  • 保留 conf/ 目錄備份。
  • 新版本 make install 覆蓋二進制,配置兼容性通常良好。
  • 平滑升級:啟動新版本 master 進程,發送 QUIT 給舊 master,實現零停機。
Copyright © Windows教程網 All Rights Reserved