Nginx 源码安装指南

本文档详细说明如何从官方源码编译并安装 Nginx,适用于需要自定义模块、优化或特定版本部署的 Linux 环境(以 CentOS / Ubuntu 为例)。 适用版本:Nginx 1.24+(示例使用最新稳定版)


1. 为什么选择源码安装

  • 精确控制 Nginx 版本(如使用 LTS 或最新特性)
  • 自定义启用/禁用模块(如 http_ssl_modulehttp_v2_module
  • 集成第三方模块(如 ngx_cache_purgelua-nginx-module
  • 优化编译参数提升性能(如指定 CPU 架构)
  • 确保同时支持 L4(TCP/UDP)和 L7(HTTP/WebSocket)代理

⚠️ 注意:Nginx 默认不启用 stream 模块(4 层代理),必须通过 --with-stream 显式开启。 ⚠️ 注意:源码安装不自动提供系统服务管理、日志轮转等功能,需手动配置。


2. 准备工作

2.1 创建专用用户(安全最佳实践)

sudo useradd -r -s /sbin/nologin nginx

2.2 创建安装目录

sudo mkdir -p /usr/local/nginx
sudo chown nginx:nginx /usr/local/nginx

3. 安装依赖

CentOS / RHEL / Rocky Linux

sudo yum install -y gcc pcre-devel zlib-devel openssl-devel libxml2-devel \
    libxslt-devel gd-devel perl-ExtUtils-Embed GeoIP-devel gperftools-devel

Ubuntu / Debian

sudo apt update
sudo apt install -y build-essential libpcre3-dev zlib1g-dev libssl-dev \
    libxml2-dev libxslt1-dev libgd-dev libgeoip-dev google-perftools-dev

说明

  • pcre:支持正则表达式(rewrite 必需)
  • zlib:支持 gzip 压缩
  • openssl:支持 HTTPS
  • 其他为可选模块依赖

4. 下载 Nginx 源码

cd /usr/src
wget https://nginx.org/download/nginx-1.26.1.tar.gz   # 替换为最新版
tar -zxvf nginx-1.26.1.tar.gz
cd nginx-1.26.1

🔍 查看最新版本:https://nginx.org/en/download.html


5. 配置编译选项

运行 ./configure --help 查看所有选项。以下为推荐生产配置:

./configure \
  --prefix=/usr/local/nginx \
  --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-http_secure_link_module \
  --with-http_sub_module \
  --with-http_dav_module \
  --with-http_slice_module \
  --with-file-aio \
  --with-threads \
  --with-pcre \
  --with-http_auth_request_module \
  --with-http_addition_module \
  --with-http_mp4_module \
  --with-http_flv_module \
  # 启用 4 层代理(TCP/UDP 负载均衡)
  --with-stream \
  --with-stream_ssl_module \
  --with-stream_realip_module \
  --with-stream_ssl_preread_module \
  --with-stream_geoip_module \
  # 安全与性能优化
  --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong' \
  --with-ld-opt='-Wl,-z,relro -Wl,-z,now'

常用模块说明

模块 作用
--with-stream 启用 4 层代理(L4),支持 TCP/UDP 负载均衡
--with-stream_ssl_module 支持 L4 SSL/TLS 透传(如 MySQL over TLS)
--with-http_ssl_module 支持 HTTPS(L7)
--with-http_v2_module 支持 HTTP/2(提升前端性能)
--with-threads 启用线程池,提升静态文件和代理性能

💡 如需添加第三方模块(如 Lua),使用 --add-module=/path/to/module


6. 编译与安装

# 编译(多核加速)
make -j$(nproc)

# 安装
sudo make install

✅ 安装完成后,主程序位于 /usr/local/nginx/sbin/nginx


7. 验证安装

# 检查版本与模块
/usr/local/nginx/sbin/nginx -V

# 测试配置
/usr/local/nginx/sbin/nginx -t

# 启动 Nginx
sudo /usr/local/nginx/sbin/nginx

# 查看进程
ps aux | grep nginx

访问服务器 IP,应看到默认欢迎页。


8. 配置 systemd 服务(可选但推荐)

创建服务文件:

sudo tee /etc/systemd/system/nginx.service << 'EOF'
[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=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

重载并启用服务:

sudo systemctl daemon-reload
sudo systemctl enable nginx
sudo systemctl start nginx

9. 示例配置:WebSocket + 4 层代理

9.1 WebSocket 代理(7 层)

nginx

server {
    listen 443 ssl http2;
    server_name ws.example.com;

    ssl_certificate     /path/to/fullchain.pem;
    ssl_certificate_key /path/to/privkey.pem;

    location /wsapp/ {
        proxy_pass http://backend_websocket_servers;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;      # 关键:升级协议
        proxy_set_header Connection "upgrade";       # 关键:触发 WebSocket
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_read_timeout 86400;  # 长连接超时(根据业务调整)
    }
}

upstream backend_websocket_servers {
    server 10.0.1.10:8080;
    server 10.0.1.11:8080;
}

9.2 4 层 TCP 代理(如数据库、MQTT、游戏服务器)

nginx

# 在 nginx.conf 的 http 块之外(顶层)
stream {
    upstream mqtt_backend {
        server 10.0.2.20:1883 max_fails=3 fail_timeout=30s;
    }

    server {
        listen 1883;
        proxy_pass mqtt_backend;
        proxy_timeout 1s;
        proxy_responses 1;
    }
}

📌 注意:stream 块必须放在 nginx.conf最外层,不能嵌套在 http 内。


10. 常见问题

Q1:WebSocket 连接失败,返回 400 或断开?

检查

  • 是否设置了 UpgradeConnection 头?
  • 后端是否支持 WebSocket 升级?
  • proxy_read_timeout 是否过短?

Q2:4 层代理不生效?

检查

  • 是否启用了 --with-stream
  • stream 块是否写在 http 外?
  • 防火墙是否放行端口?

Q3: configure: error: SSL modules require the OpenSSL library.

解决:确保已安装 openssl-devel(CentOS)或 libssl-dev(Ubuntu)。

Q4: 启动时报错 nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)

解决:停止其他 Web 服务(如 Apache):

sudo systemctl stop httpd   # CentOS
sudo systemctl stop apache2 # Ubuntu

Q5: 如何升级 Nginx 而不中断服务?

平滑升级步骤

  1. 编译新版本(不执行 make install
  2. 备份旧二进制:mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.old
  3. 复制新二进制:cp objs/nginx /usr/local/nginx/sbin/
  4. 测试配置:/usr/local/nginx/sbin/nginx -t
  5. 发送升级信号:kill -USR2 $(cat /usr/local/nginx/logs/nginx.pid)
  6. 验证后关闭旧进程:kill -QUIT $(cat /usr/local/nginx/logs/nginx.pid.oldbin)

results matching ""

    No results matching ""