跳到主要内容

window中使用nginx

一般地,使用nginx都是在linux服务器上,对于没有服务器来说, 在window上使用也可以,需要在window上安装nginx,在window上去操作nginx

window安装nginx​

  • 1、官网下载window版本nginx
  • 2、启动nginx
    • 进入nginx目录,执行start nginx
  • 3、验证nginx是否启动
    • 访问 http://localhost:80)(默认端口),若显示欢迎页则成功。
    • 修改端口号,通过config/nginx.conf中的listen 80 修改为其他端口号

注意,不要直接双击nginx.exe,可能会有问题,进入nginx目录,启动nginx即可

配置反向代理​

如:将前端项目请求代理到本地开发服务器

  • 通过配置文件 conf/nginx.conf
bash
server {
listen 80;
server_name localhost;

# 静态文件服务(可选)
location / {
root html;
index index.html;
try_files $uri $uri/ /index.html; # 支持Vue/React的history模式
}

# 反向代理API请求
location /api/ {
proxy_pass http://localhost:3000; # 后端服务器地址
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

关键指令:

  • proxy_pass:指定后端服务地址 (需要反向代理的地址)
  • proxy_set_header:传递客户端真实IP和协议信息
  • try_files:处理前端路由的history模式

设置host​

  • 1、如果nginx配置了域名反向代理
bash
server_name xxx.xx.com
  • 2、设置本地host,来解析ip地址
bash
127.0.0.1 xxx.xx.com