插件窝 干货文章 Nginx怎么编译并安装

Nginx怎么编译并安装

Nginx HTTP 编译 module 191    来源:    2025-04-23

Nginx 编译安装指南

Nginx 是一个高性能的 HTTP 和反向代理服务器。以下是编译安装 Nginx 的详细步骤:

1. 准备工作

安装依赖项

# 对于基于 Debian/Ubuntu 的系统
sudo apt update
sudo apt install -y build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev

# 对于基于 RHEL/CentOS 的系统
sudo yum groupinstall -y "Development Tools"
sudo yum install -y pcre pcre-devel zlib zlib-devel openssl openssl-devel

下载 Nginx 源码

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

<version> 替换为你需要的 Nginx 版本号,如 1.25.3

2. 配置编译选项

./configure \
    --prefix=/usr/local/nginx \
    --sbin-path=/usr/sbin/nginx \
    --conf-path=/etc/nginx/nginx.conf \
    --pid-path=/var/run/nginx.pid \
    --error-log-path=/var/log/nginx/error.log \
    --http-log-path=/var/log/nginx/access.log \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_realip_module \
    --with-http_stub_status_module \
    --with-threads \
    --with-file-aio

常用编译选项说明: - --prefix: 安装目录 - --with-http_ssl_module: 启用 HTTPS 支持 - --with-http_v2_module: 启用 HTTP/2 支持 - --with-http_realip_module: 获取客户端真实 IP - --with-http_stub_status_module: 启用状态监控页面

运行 ./configure --help 查看所有可用选项。

3. 编译和安装

make
sudo make install

4. 验证安装

nginx -v

5. 创建系统服务(可选)

创建 systemd 服务文件 /etc/systemd/system/nginx.service

[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/usr/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
TimeoutStopSec=5
KillMode=mixed

[Install]
WantedBy=multi-user.target

启用并启动服务:

sudo systemctl enable nginx
sudo systemctl start nginx

6. 常用命令

  • 启动: nginxsystemctl start nginx
  • 停止: nginx -s stopsystemctl stop nginx
  • 重载配置: nginx -s reloadsystemctl reload nginx
  • 测试配置: nginx -t

注意事项

  1. 编译前确保系统有足够的磁盘空间
  2. 如果遇到依赖问题,根据错误提示安装相应的开发包
  3. 生产环境建议禁用不需要的模块以提高安全性
  4. 防火墙需要开放 80 和 443 端口(如果需要)

如需更高级的配置,可以参考 Nginx 官方文档或使用 nginx -V 查看当前编译参数。