rockylinux10编译安装nginx

1. 环境准备与安装依赖

sudo dnf update -y
sudo dnf install -y gcc gcc-c++ make zlib-devel openssl-devel pcre2-devel wget tar

接着,创建一个用于运行 Nginx 的专用系统用户,这有助于提升安全性

sudo useradd -M -s /sbin/nologin nginx

 2. 下载并解压源码

进入 /opt 目录(或其他你喜欢的目录),从 Nginx 官网下载稳定版本的源码包

cd /opt
sudo wget https://nginx.org/download/nginx-1.28.0.tar.gz
sudo tar -zxvf nginx-1.28.0.tar.gz

 3. 配置编译选项

进入解压后的源码目录,运行 ./configure 脚本。这一步非常关键,你可以在此定制安装路径和需要启用的模块

cd /opt/nginx-1.28.0

下面是一个包含常用模块的配置示例

./configure \
    --prefix=/usr/local/nginx \
    --user=nginx \
    --group=nginx \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_realip_module \
    --with-http_addition_module \
    --with-http_sub_module \
    --with-http_dav_module \
    --with-http_flv_module \
    --with-http_mp4_module \
    --with-http_gunzip_module \
    --with-http_gzip_static_module \
    --with-http_random_index_module \
    --with-http_secure_link_module \
    --with-http_stub_status_module \
    --with-http_auth_request_module \
    --with-mail \
    --with-mail_ssl_module \
    --with-file-aio \
    --with-stream \
    --with-stream_ssl_module \
    --with-pcre
  • --prefix=/usr/local/nginx: 指定 Nginx 的安装根目录。

  • --with-http_ssl_module: 启用 HTTPS(SSL/TLS)支持-7

  • --with-http_v2_module: 启用 HTTP/2 协议支持。

  • --with-stream: 启用 TCP/UDP 代理(Stream)模块。

4. 编译与安装

执行 make 命令进行编译。为了加快速度,可以使用 -j 参数指定并行任务数。

make -j$(nproc)

编译完成后,执行安装:

sudo make install

5. 创建 Systemd 服务并启动

为了让 Nginx 能通过 systemctl 命令方便地管理,需要手动创建一个 systemd 服务文件。

sudo tee /usr/lib/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=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

保存文件后,重新加载 systemd 配置,并设置 Nginx 开机自启:

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

6. 防火墙与验证

如果防火墙开启,需要放行 HTTP 和 HTTPS 服务:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

最后,验证 Nginx 是否运行正常:

sudo systemctl status nginx

 补充说明

  • 安装目录:按照上述配置,Nginx 会安装在 /usr/local/nginx 目录下。配置文件位于 /usr/local/nginx/conf/nginx.conf

  • 查看配置选项:在配置前,可以运行 ./configure --help 查看所有可用的编译选项

  • 报错解决:如果遇到 ./configure: error: the HTTP rewrite module requires the PCRE library. 错误,说明缺少 PCRE 库,请确保已安装 pcre2-devel



posted on 2026-07-08 14:34  wtsgtc  阅读(11)  评论(0)    收藏  举报

导航