插件窝 干货文章 Nginx怎么重新编译添加模块

Nginx怎么重新编译添加模块

Nginx 模块 module 编译 339    来源:    2025-04-22

Nginx 重新编译添加模块指南

准备工作

  1. 备份现有配置

    sudo cp -r /etc/nginx /etc/nginx_backup
    
  2. 查看当前Nginx版本和编译参数

    nginx -V
    

    记录输出中的configure arguments:后面的所有参数,这些在重新编译时需要用到。

重新编译步骤

  1. 下载相同版本的Nginx源码

    wget http://nginx.org/download/nginx-<version>.tar.gz
    tar -zxvf nginx-<version>.tar.gz
    cd nginx-<version>
    
  2. 配置编译参数: 使用之前记录的参数,并添加新模块。例如要添加http_ssl_module

    ./configure <原有参数> --with-http_ssl_module
    

    常见模块:

    • --with-http_ssl_module (SSL支持)
    • --with-http_v2_module (HTTP/2支持)
    • --with-http_realip_module (真实IP模块)
    • --with-http_gzip_static_module (gzip静态压缩)
  3. 编译

    make
    

    不要运行make install,这会覆盖配置文件

  4. 替换二进制文件

    sudo cp /usr/sbin/nginx /usr/sbin/nginx.old
    sudo cp objs/nginx /usr/sbin/nginx
    
  5. 测试新配置

    sudo nginx -t
    
  6. 平滑重启Nginx

    sudo systemctl restart nginx
    

    sudo kill -USR2 `cat /var/run/nginx.pid`
    

验证模块是否添加成功

nginx -V

检查输出中是否包含新添加的模块。

注意事项

  1. 确保添加的模块与当前Nginx版本兼容
  2. 如果添加的是第三方模块,需要先下载模块源码并在configure时通过--add-module=/path/to/module指定
  3. 编译环境需要安装相关依赖,如gcc、make、PCRE、zlib等
  4. 如果遇到依赖问题,可能需要安装开发包,如libssl-dev

常见问题解决

问题1:缺少依赖

./configure: error: the HTTP rewrite module requires the PCRE library.

解决:安装PCRE开发包

sudo apt-get install libpcre3 libpcre3-dev

问题2:版本不匹配

nginx: [emerg] module "/path/to/module.so" is not binary compatible

解决:确保模块与Nginx版本匹配,或从源码重新编译模块