直接用包管理器安装Nginx最省事,适合大多数场景——无需编译、依赖自动安装、配置预置完整、支持systemd统一管理;Ubuntu/Debian用apt,RHEL系需先启用EPEL源;安装后需验证状态、版本、本地及浏览器访问,并检查防火墙、监听地址和配置语法。
直接用包管理器安装是最省事的方式,适合大多数场景——不用编译、依赖自动装好、配置文件预置完整、服务能用 systemd 统一管理。
Ubuntu/Debian 系统(apt)
更新源并安装:
- 运行 sudo apt update 同步软件包列表
- 执行 sudo apt install nginx -y 安装主程序(会自动拉取 openssl、systemd 等依赖)
- 启动服务:sudo systemctl start nginx
- 设为开机自启:sudo systemctl enable nginx
CentOS/RHEL/AlmaLinux/Rocky Linux(dnf 或 yum)
这些系统默认仓库一般不带 Nginx,需先启用 EPEL 源:
- RHEL 8+ / AlmaLinux 8+ / Rocky Linux 8+:sudo dnf install epel-release -y && sudo dnf install nginx -y
- CentOS/RHEL 7:sudo yum install epel-release -y && sudo yum install nginx -y
- 启动并开机自启:sudo systemctl start nginx && sudo systemctl enable nginx
验证是否装好
装完别急着改配置,先确认服务跑起来了:
- 查状态:sudo systemctl status nginx → 显示 active (running) 就成功了
- 看版本:nginx -v 输出类似 nginx version: nginx/1.24.0
- 本地测试:curl -I http://127.0.0.1 应返回 HTTP/1.1 200 OK
- 浏览器访问服务器 IP,看到 “Welcome to nginx!” 页面即表示 Web 服务已就绪
装完就能用,但别跳过这几步
基础服务跑通后,建议顺手做三件事:
- 检查防火墙:若开了 firewalld 或 ufw,需放行 80 端口(sudo firewall-cmd --add-port=80/tcp --permanent && sudo firewall-cmd --reload)
- 确认监听地址:sudo ss -tlnp | grep :80,确保 nginx 在 0.0.0.0:80 或 [::]:80 上监听
- 修改配置前先测试语法:sudo nginx -t,通过后再 sudo systemctl reload nginx