插件窝 干货文章 centos8自定义目录安装nginx的方法

centos8自定义目录安装nginx的方法

Nginx 安装 opt systemctl 822    来源:    2025-04-27

CentOS 8 自定义目录安装 Nginx 的方法

在 CentOS 8 上自定义安装目录安装 Nginx 需要从源代码编译安装。以下是详细步骤:

1. 安装必要的依赖

dnf install -y gcc make pcre-devel zlib-devel openssl-devel wget

2. 创建自定义目录

假设你想将 Nginx 安装在 /opt/nginx 目录下:

mkdir -p /opt/nginx

3. 下载 Nginx 源代码

wget http://nginx.org/download/nginx-1.25.3.tar.gz
tar -zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3

(请将版本号替换为最新的稳定版本)

4. 配置编译选项

./configure \
--prefix=/opt/nginx \
--sbin-path=/opt/nginx/sbin/nginx \
--conf-path=/opt/nginx/conf/nginx.conf \
--pid-path=/opt/nginx/logs/nginx.pid \
--error-log-path=/opt/nginx/logs/error.log \
--http-log-path=/opt/nginx/logs/access.log \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-pcre \
--with-file-aio \
--with-stream \
--with-stream_ssl_module

5. 编译并安装

make && make install

6. 创建系统服务文件

创建 /etc/systemd/system/nginx.service 文件:

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

[Service]
Type=forking
PIDFile=/opt/nginx/logs/nginx.pid
ExecStartPre=/opt/nginx/sbin/nginx -t
ExecStart=/opt/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

7. 启用并启动 Nginx 服务

systemctl daemon-reload
systemctl enable nginx
systemctl start nginx

8. 验证安装

/opt/nginx/sbin/nginx -v
systemctl status nginx
curl http://localhost

9. 配置环境变量(可选)

为了方便使用,可以将 Nginx 可执行文件路径添加到 PATH 中:

echo 'export PATH=$PATH:/opt/nginx/sbin' >> ~/.bashrc
source ~/.bashrc

注意事项

  1. 自定义安装后,配置文件位于 /opt/nginx/conf/nginx.conf
  2. 日志文件默认存放在 /opt/nginx/logs/ 目录下
  3. 如果需要添加更多模块,可以在 configure 步骤中添加相应选项
  4. 更新 Nginx 时需要重新编译安装

卸载方法

如果需要卸载自定义安装的 Nginx:

systemctl stop nginx
systemctl disable nginx
rm -rf /opt/nginx
rm -f /etc/systemd/system/nginx.service
systemctl daemon-reload

这样就完成了在 CentOS 8 上自定义目录安装 Nginx 的全部过程。