一、环境确认

首先确认你的操作系统类型,这决定了使用哪个包管理工具:

cat /etc/os-release

在这里插入图片描述

操作系统 包管理工具
Ubuntu/Debian apt
CentOS/RHEL/RockyLinux yum 或 dnf
Alibaba Cloud Linux yum

二、Ubuntu/Debian 系统安装步骤

1. 更新软件源并安装

sudo apt update
sudo apt install nginx -y

2. 启动并设置开机自启

# 启动 Nginx 服务
sudo systemctl start nginx

# 设置开机自启
sudo systemctl enable nginx

# 查看运行状态(应显示 active (running))
sudo systemctl status nginx

在这里插入图片描述

3. 配置防火墙(如果使用 ufw)

# 允许 Nginx 的 HTTP 流量
sudo ufw allow 'Nginx HTTP'

# 或直接开放 80 端口
sudo ufw allow 80/tcp

# 查看防火墙状态
sudo ufw status

三、CentOS/RHEL 系统安装步骤

1. 安装 EPEL 源并安装 Nginx

# 安装 EPEL 扩展源(CentOS 7/8 需要)
sudo yum install epel-release -y

# 安装 Nginx
sudo yum install nginx -y

2. 启动并设置开机自启

sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl status nginx

3. 开放防火墙端口(如果使用 firewalld)

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

四、验证安装是否成功

方法一:本地 curl 测试

curl -I http://localhost

在这里插入图片描述

方法二:浏览器访问

在浏览器中输入你的服务器公网 IP,看到 “Welcome to nginx” 页面即表示安装成功
在这里插入图片描述

五、常用管理命令

操作 命令
启动 sudo systemctl start nginx
停止 sudo systemctl stop nginx
重启 sudo systemctl restart nginx
重载配置 sudo systemctl reload nginx
查看状态 sudo systemctl status nginx
测试配置 sudo nginx -t
查看错误日志 sudo tail -f /var/log/nginx/error.log

六、默认网站根目录

操作系统 默认根目录 说明
Ubuntu/Debian /var/www/html/ apt 安装的默认目录
CentOS/RHEL /usr/share/nginx/html/ yum 安装的默认目录
源码编译 /usr/local/nginx/html/ 编译时指定的路径

七、查看当前 Nginx 根目录

# 查看 Nginx 配置中的根目录
grep -r "root" /etc/nginx/conf.d/
grep -r "root" /etc/nginx/sites-enabled/

# 或查看默认配置
cat /etc/nginx/sites-available/default | grep root

八、 配置文件地址

📁 配置文件位置速查表

安装方式 主配置文件 站点配置目录 适用系统/场景
包管理器安装 (如 apt 或 yum) /etc/nginx/nginx.conf /etc/nginx/conf.d/ 或 /etc/nginx/sites-enabled/ 主流 Linux 发行版 (Ubuntu, CentOS, Debian 等)
源码编译安装 /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/conf.d/ (需手动创建) 追求定制化、需要特定模块的场景
宝塔面板安装 /www/server/nginx/conf/nginx.conf /www/server/panel/vhost/nginx/

🧭 快速确认你的配置文件路径

如果你不确定当前的 Nginx 属于哪种情况,可以使用下面任一命令来确认:

方法一:使用 nginx -t 命令

这是最直接的方法。执行此命令测试配置语法时,它会明确告诉你正在使用的主配置文件路径。

nginx -t

输出示例:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

在这里插入图片描述

方法二:使用 find 命令搜索

如果 nginx -t 命令不可用,也可以在全局搜索配置文件。

sudo find / -name "nginx.conf" 2>/dev/null
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐