nginx配置反向代理解决跨域

一、下载nginx

 避免少走弯路,下载稳定版

二、启动nginx 两种方法

1、双击nginx.exe

2、cmd转到nginx文件夹输入 start nginx

会有一个弹出框一闪而过,然后在浏览器输入localhost,页面显示 welcome 就算启动成功

三、nginx常用命令

start nginx   //启动nginx

nginx -s stop   //强制关闭

nginx -s  quit   //安全关闭

nginx -s reload  //重启

nginx -s reopen  //打开日志文件

四、配置跨域

1、原理

前端:localhost:8081 访问 后端:localhost:7070

用nginx指定一个端口如:8080,把两个都代理到同一端口,解决跨域

2、配置文件

为了方便,我们在conf文件夹新建一个proxy.conf

server{
  #指定统一的端口
  listen     8080;
  #要监听的IP地址,本地就是localhost
  server_name   localhost;
  #对对应的url进行反向代理
  #/demo 指可以访问 /demo1,也可以访问 /demo/index
  #/demo/ 只可以访问 /demo/index
  location /demo {
      #你前端的地址
      proxy_pass  http://localhost:8081;  
  }
  
  location  /api {
      #后端地址
      proxy_pass  http://localhost:7070;   
  }
} 

在nginx.conf引入proxy.conf

在http里加一行

include      proxy.conf;

每次改变配置文件,必须运行  nginx -s reload来重启下

这样localhost:8080/demo就可以访问前端,localhost:8080/api可以访问后端

 

猜你喜欢

转载自www.cnblogs.com/hess/p/12704296.html