一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Linux 如何通过包管理器快速安装 Nginx 服务

时间:2026-09-02 08:46:49 编辑:袖梨 来源:一聚教程网

直接用包管理器安装Nginx最省事,适合大多数场景——无需编译、依赖自动安装、配置预置完整、支持systemd统一管理;Ubuntu/Debian用apt,RHEL系需先启用EPEL源;安装后需验证状态、版本、本地及浏览器访问,并检查防火墙、监听地址和配置语法。

直接用包管理器安装是最省事的方式,适合大多数场景——不用编译、依赖自动装好、配置文件预置完整、服务能用 systemd 统一管理。

Ubuntu/Debian 系统(apt)

更新源并安装:

  1. 运行 sudo apt update 同步软件包列表
  2. 执行 sudo apt install nginx -y 安装主程序(会自动拉取 openssl、systemd 等依赖)
  3. 启动服务:sudo systemctl start nginx
  4. 设为开机自启:sudo systemctl enable nginx

CentOS/RHEL/AlmaLinux/Rocky Linux(dnf 或 yum)

这些系统默认仓库一般不带 Nginx,需先启用 EPEL 源:

  1. RHEL 8+ / AlmaLinux 8+ / Rocky Linux 8+:sudo dnf install epel-release -y && sudo dnf install nginx -y
  2. CentOS/RHEL 7:sudo yum install epel-release -y && sudo yum install nginx -y
  3. 启动并开机自启:sudo systemctl start nginx && sudo systemctl enable nginx

验证是否装好

装完别急着改配置,先确认服务跑起来了:

  1. 查状态:sudo systemctl status nginx → 显示 active (running) 就成功了
  2. 看版本:nginx -v 输出类似 nginx version: nginx/1.24.0
  3. 本地测试:curl -I http://127.0.0.1 应返回 HTTP/1.1 200 OK
  4. 浏览器访问服务器 IP,看到 “Welcome to nginx!” 页面即表示 Web 服务已就绪

装完就能用,但别跳过这几步

基础服务跑通后,建议顺手做三件事:

  1. 检查防火墙:若开了 firewalld 或 ufw,需放行 80 端口(sudo firewall-cmd --add-port=80/tcp --permanent && sudo firewall-cmd --reload
  2. 确认监听地址:sudo ss -tlnp | grep :80,确保 nginx 在 0.0.0.0:80 或 [::]:80 上监听
  3. 修改配置前先测试语法:sudo nginx -t,通过后再 sudo systemctl reload nginx

热门栏目