以下是在不同操作系统上安装和运行 Nginx 的详细步骤:
一、Ubuntu/Debian 系统
1. 安装 Nginx
# 更新包索引
sudo apt update
# 安装 Nginx
sudo apt install nginx
# 验证安装
nginx -v # 输出类似: nginx version: nginx/1.18.0
2. 控制 Nginx 服务
# 启动服务
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 检查服务状态
sudo systemctl status nginx
# 停止服务
sudo systemctl stop nginx
# 重启服务(修改配置后常用)
sudo systemctl restart nginx
# 重新加载配置(不中断现有连接)
sudo systemctl reload nginx
3. 防火墙配置
# 允许 HTTP 和 HTTPS 流量
sudo ufw allow 'Nginx HTTP' # 仅允许 80 端口
sudo ufw allow 'Nginx HTTPS' # 仅允许 443 端口
sudo ufw allow 'Nginx Full' # 同时允许 80 和 443 端口
二、CentOS/RHEL 系统
1. 安装 Nginx
# 添加 Nginx 官方仓库
sudo tee /etc/yum.repos.d/nginx.repo <<EOF
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/\$releasever/\$basearch/
gpgcheck=0
enabled=1
EOF
# 安装 Nginx
sudo yum install nginx
# 验证安装
nginx -v
2. 控制 Nginx 服务
# 启动服务
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 其他命令(与 Ubuntu 相同)
sudo systemctl {stop|restart|reload|status} nginx
3. 防火墙配置
# 允许 HTTP 和 HTTPS 流量
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
三、macOS(使用 Homebrew)
1. 安装 Homebrew(如未安装)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
2. 安装和管理 Nginx
# 安装 Nginx
brew install nginx
# 启动服务
brew services start nginx # 后台运行并开机自启
# 或临时启动(不设开机自启)
nginx
# 停止服务
brew services stop nginx
# 或直接杀进程
killall nginx
# 配置文件位置
/usr/local/etc/nginx/nginx.conf
# 访问测试
http://localhost:8080 # macOS 默认监听 8080 端口
四、Windows 系统
1. 下载与安装
- 访问 Nginx 官网下载页面,下载 Windows 版本(.zip 文件)。
- 解压到指定目录(如
C:\nginx
)。
2. 控制 Nginx
# 进入 Nginx 目录
cd C:\nginx
# 启动 Nginx
start nginx.exe
# 停止 Nginx
nginx.exe -s stop # 快速停止
# 或
nginx.exe -s quit # 优雅停止
# 重新加载配置
nginx.exe -s reload
# 验证配置文件语法
nginx.exe -t
3. 访问测试
打开浏览器访问 http://localhost
,若看到 "Welcome to nginx!" 页面,则安装成功。
五、验证安装是否成功
- 浏览器访问:
打开浏览器,输入http://服务器IP地址
(或http://localhost
),若看到 Nginx 欢迎页面,则安装成功。 检查进程:
ps -ef | grep nginx # 应看到 master 和 worker 进程
端口监听:
netstat -tulpn | grep :80 # 检查 80 端口是否被监听
六、配置文件位置
- Linux:
/etc/nginx/nginx.conf
(主配置),/etc/nginx/conf.d/
(站点配置) - macOS(Homebrew):
/usr/local/etc/nginx/nginx.conf
- Windows:
C:\nginx\conf\nginx.conf
七、常见问题
端口冲突:
- 若 80 端口被占用,修改
nginx.conf
中的listen
指令(如改为 8080)。
- 若 80 端口被占用,修改
权限问题:
- Linux 下若无法监听 80/443 端口,可使用
sudo
或调整 SELinux/AppArmor 配置。
- Linux 下若无法监听 80/443 端口,可使用
配置语法错误:
- 修改配置后,使用
nginx -t
检查语法,再nginx -s reload
重新加载。
- 修改配置后,使用
八、下一步
- 配置虚拟主机:创建多个网站配置文件(
.conf
)放在/etc/nginx/conf.d/
目录下。 - 配置 HTTPS:使用 Let's Encrypt 免费证书实现 HTTPS。
- 负载均衡:配置 upstream 模块将请求分发到多个后端服务器。
评论 (0)