插件窝 干货文章 源码编译安装Nginx的方法是什么

源码编译安装Nginx的方法是什么

Nginx 编译 with 启用 68    来源:    2025-04-23

Nginx 源码编译安装方法

准备工作

  1. 安装编译工具和依赖库

    # CentOS/RHEL
    sudo yum install -y gcc make pcre-devel zlib-devel openssl-devel
    
    # Ubuntu/Debian
    sudo apt-get install -y build-essential libpcre3-dev zlib1g-dev libssl-dev
    
  2. 下载Nginx源码包

    wget http://nginx.org/download/nginx-<version>.tar.gz
    tar -zxvf nginx-<version>.tar.gz
    cd nginx-<version>
    

    (将<version>替换为实际版本号,如1.25.3)

编译安装步骤

  1. 配置编译选项

    ./configure \
     --prefix=/usr/local/nginx \
     --with-http_ssl_module \
     --with-http_v2_module \
     --with-http_realip_module \
     --with-http_stub_status_module \
     --with-threads \
     --with-stream
    

    (可根据需要添加或删除模块)

  2. 编译并安装

    make
    sudo make install
    
  3. 验证安装

    /usr/local/nginx/sbin/nginx -v
    

后续配置

  1. 创建系统服务(可选):

    sudo nano /etc/systemd/system/nginx.service
    

    添加以下内容:

    [Unit]
    Description=The NGINX HTTP and reverse proxy server
    After=syslog.target 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
    
  2. 启用并启动服务

    sudo systemctl enable nginx
    sudo systemctl start nginx
    

常用编译选项说明

  • --prefix:指定安装目录
  • --with-http_ssl_module:启用HTTPS支持
  • --with-http_v2_module:启用HTTP/2支持
  • --with-http_stub_status_module:启用状态监控页面
  • --with-stream:启用TCP/UDP代理功能
  • --with-threads:启用线程池支持

注意事项

  1. 编译前可通过./configure --help查看所有可用选项
  2. 如果需要添加新模块,需要重新编译安装
  3. 默认配置文件位于/usr/local/nginx/conf/nginx.conf
  4. 日志文件默认位于/usr/local/nginx/logs/