一、Linux 系统安装
1. CentOS / RHEL 系统
使用 yum 包管理器安装:
# 1. 更新系统包
sudo yum update -y# 2. 安装 Nginx
sudo yum install -y nginx# 3. 启动 Nginx 服务
sudo systemctl start nginx# 4. 设置开机自启
sudo systemctl enable nginx# 5. 验证安装状态
sudo systemctl status nginx
2. Ubuntu / Debian 系统
使用 apt 包管理器安装:
# 1. 更新系统包
sudo apt update -y# 2. 安装 Nginx
sudo apt install -y nginx# 3. 启动 Nginx 服务
sudo systemctl start nginx# 4. 设置开机自启
sudo systemctl enable nginx# 5. 验证安装状态
sudo systemctl status nginx
3. 验证安装成功
在浏览器中访问服务器 IP 地址(如 http://your-server-ip ),如果看到 "Welcome to nginx!" 页面,则表示安装成功。
二、Windows 系统安装
1. 下载 Nginx
- 访问 Nginx 官网
- 下载稳定版本(Stable version)的 Windows 版本(如 nginx-1.24.0.zip )
2. 解压安装
- 将下载的 ZIP 文件解压到本地目录(如 C:\nginx )
- 解压后目录结构应包含 nginx.exe 可执行文件
3. 启动 Nginx 方法 1:命令行启动
# 进入 Nginx 目录
cd C:\nginx# 启动 Nginx
start nginx
``` 方法 2:直接双击启动
双击 nginx.exe 文件即可启动服务。### 4. 验证安装成功
在浏览器中访问 http://localhost ,如果看到 "Welcome to nginx!" 页面,则表示安装成功。### 5. 基本操作命令
进入 Nginx 目录
cd C:\nginx
启动 Nginx
start nginx
停止 Nginx(快速停止)
nginx -s stop
停止 Nginx(优雅停止)
nginx -s quit
重新加载配置
nginx -s reload
查看版本
nginx -v
## 三、Nginx 基本配置
### 1. Linux 系统配置文件位置
- 主配置文件: /etc/nginx/nginx.conf
- 站点配置目录: /etc/nginx/conf.d/
- 默认站点配置: /etc/nginx/conf.d/default.conf
### 2. Windows 系统配置文件位置
- 主配置文件: C:\nginx\conf\nginx.conf
### 3. 基本配置示例(用于部署前端项目)
编辑配置文件(如 /etc/nginx/conf.d/default.conf 或 C:\nginx\conf\nginx.conf ),添加以下内容:
server {
listen 80;
server_name localhost;
# 前端项目根目录
root /usr/share/nginx/html; # Linux 路径
# root C:/nginx/html; # Windows 路径
index index.html index.htm;
# 处理前端路由(防止刷新 404)
location / {
try_files $uri $uri/ /index.html;
}
# 代理后端 API
location /prod-api/ {
proxy_pass http://localhost:8080/; # 后端服务地址
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For
$proxy_add_x_forwarded_for;
}
}
### 4. 重新加载配置
Linux
sudo nginx -s reload
Windows
nginx -s reload
## 四、常见问题及解决方案
### 1. 端口占用
如果 80 端口已被占用,修改配置文件中的 listen 指令,使用其他端口(如 8080):
server {
listen 8080;
# 其他配置...
}
### 2. 权限问题(Linux)
如果访问静态文件出现 403 错误,检查文件权限:
设置正确的权限
sudo chmod -R 755 /usr/share/nginx/html
sudo chown -R nginx:nginx /usr/share/nginx/html
### 3. 防火墙设置(Linux)
如果无法访问 Nginx,检查防火墙是否允许 80 端口:
允许 80 端口
sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --reload
## 五、验证安装成功
1. 查看版本 :
nginx -v
2. 访问默认页面 :
在浏览器中输入 http://localhost 或服务器 IP,看到 "Welcome to nginx!" 页面即成功。
3. 检查服务状态 :
Linux
sudo systemctl status nginx
Windows(任务管理器查看进程)
或使用命令:tasklist | findstr nginx
安装完成后,即可将前端项目的 dist 文件夹内容复制到 Nginx 的根目录(如 /usr/share/nginx/html 或 C:\nginx\html ),然后通过浏览器访问部署的项目。