插件窝 干货文章 在Centos下怎么安装Nginx

在Centos下怎么安装Nginx

Nginx 安装 sudo bash 795    来源:    2025-04-25

在 CentOS 系统上安装 Nginx 可以通过以下步骤完成,这里提供两种主流方法:YUM 仓库安装(推荐)和源码编译安装


方法一:通过 YUM 仓库安装(推荐)

1. 更新系统包

sudo yum update -y

2. 安装 EPEL 仓库(Extra Packages for Enterprise Linux)

Nginx 在默认的 CentOS 仓库中可能不存在,需要先安装 EPEL:

sudo yum install epel-release -y

3. 安装 Nginx

sudo yum install nginx -y

4. 启动并设置开机自启

sudo systemctl start nginx
sudo systemctl enable nginx

5. 验证安装

  • 检查服务状态: bash sudo systemctl status nginx
  • 访问默认页面: 在浏览器中输入服务器 IP 地址,看到 Welcome to Nginx 页面即表示成功。

6. 配置防火墙(如果启用)

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

方法二:源码编译安装(适合自定义需求)

1. 安装编译依赖

sudo yum groupinstall "Development Tools" -y
sudo yum install pcre-devel zlib-devel openssl-devel -y

2. 下载 Nginx 源码

官网 获取最新稳定版链接:

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

3. 编译并安装

./configure --prefix=/usr/local/nginx --with-http_ssl_module
make
sudo make install

4. 启动 Nginx

sudo /usr/local/nginx/sbin/nginx

5. 设置系统服务(可选)

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

[Unit]
Description=The Nginx HTTP Server
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target

然后启用服务:

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

常见问题

  1. 端口冲突:如果 Apache 或其他服务占用了 80 端口,需先停止它们。

    sudo systemctl stop httpd
    
  2. SELinux 拦截:临时禁用 SELinux 或调整策略:

    sudo setenforce 0  # 临时关闭
    
  3. 验证配置文件

    sudo nginx -t  # 检查配置语法
    

总结

  • 推荐方法:使用 YUM 安装(简单、易维护)。
  • 高级需求:源码编译安装(灵活定制模块)。

安装完成后,配置文件默认路径: - YUM 安装:/etc/nginx/nginx.conf - 源码安装:/usr/local/nginx/conf/nginx.conf