Nginx 在 Windows 上有预编译的二进制版本,本章节将介绍如何在 Windows 系统上安装和配置 Nginx。
将下载的 zip 文件解压到您选择的目录,例如:
C:\nginx
解压后的目录结构如下:
nginx/
├── conf/ # 配置文件目录
│ ├── fastcgi.conf
│ ├── fastcgi_params
│ ├── koi-utf
│ ├── koi-win
│ ├── mime.types
│ ├── nginx.conf
│ ├── scgi_params
│ ├── uwsgi_params
│ └── win-utf
├── contrib/ # 脚本和工具
├── docs/ # 文档
├── html/ # 默认网站根目录
│ ├── 50x.html
│ └── index.html
├── logs/ # 日志文件目录
│ ├── access.log
│ └── error.log
└── nginx.exe # Nginx 可执行文件
直接双击 nginx.exe 文件启动 Nginx。
打开命令提示符(CMD)或 PowerShell,进入 Nginx 目录:
cd C:\nginx
nginx
使用第三方工具将 Nginx 注册为 Windows 服务:
# 下载 NSSM (Non-Sucking Service Manager)
# https://nssm.cc/download
# 安装服务
nssm install nginx C:\nginx\nginx.exe
# 启动服务
nssm start nginx
# 停止服务
nssm stop nginx
# 重启服务
nssm restart nginx
# 删除服务
nssm remove nginx
# 检查版本
nginx -v
# 测试配置
nginx -t
# 测试服务
curl http://localhost
在浏览器中访问 http://localhost,看到 "Welcome to nginx!" 页面即表示安装成功。
# 启动 Nginx
nginx
# 停止 Nginx(快速停止)
nginx -s stop
# 优雅退出(等待当前请求完成)
nginx -s quit
# 重新加载配置
nginx -s reload
# 重新打开日志文件
nginx -s reopen
# 测试配置文件
nginx -t
# 显示版本信息
nginx -v
# 显示版本和编译信息
nginx -V
C:\nginx\conf\nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
如果 80 端口被占用,可以修改为其他端口:
server {
listen 8080; # 修改为 8080 端口
server_name localhost;
location / {
root html;
index index.html index.htm;
}
}
修改后重新加载配置:
nginx -t
nginx -s reload
# 允许 HTTP (80 端口)
netsh advfirewall firewall add rule name="nginx" dir=in action=allow protocol=TCP localport=80
# 允许 HTTPS (443 端口)
netsh advfirewall firewall add rule name="nginx https" dir=in action=allow protocol=TCP localport=443
# 删除规则
netsh advfirewall firewall delete rule name="nginx"
C:\nginx\logs\
├── access.log # 访问日志
└── error.log # 错误日志
# 实时查看错误日志
Get-Content C:\nginx\logs\error.log -Wait -Tail 50
# 实时查看访问日志
Get-Content C:\nginx\logs\access.log -Wait -Tail 50
# 查看 Nginx 进程
Get-Process nginx
# 查看端口占用
netstat -ano | findstr :80
# 结束占用端口的进程
taskkill /PID <进程ID> /F
以管理员身份运行命令提示符或 PowerShell。
# 测试配置文件
nginx -t
# 检查错误日志
type C:\nginx\logs\error.log
# 检查进程
tasklist | findstr nginx
# 强制结束进程
taskkill /F /IM nginx.exe
C:\nginx\nginx.exeC:\nginxnssm install nginx C:\nginx\nginx.exe
nssm set nginx Start SERVICE_AUTO_START
Win + R,输入 shell:startup# 停止 Nginx
nginx -s stop
# 删除服务(如果使用 NSSM)
nssm remove nginx
# 删除 Nginx 目录
rmdir /s C:\nginx
worker_processes auto; # 自动检测 CPU 核心数
events {
worker_connections 2048; # 增加连接数
}
http {
gzip on;
gzip_min_length 1000;
gzip_types text/plain text/css application/json;
}