Galan小屋

welcome my blog

nginx用反向代理机制解决跨域的问题

By galan99

发表于 2018-09-29

nginx反向代理实现跨域和便捷的前后端联调



启动本地nginx



进入本地nginx目录执行以下命令

/usr/local/webserver/nginx/sbin/start nginx                # 开启nginx
/usr/local/webserver/nginx/sbin/nginx -s reload            # 重新载入配置文件
/usr/local/webserver/nginx/sbin/nginx -s reopen            # 重启 Nginx
/usr/local/webserver/nginx/sbin/nginx -s stop              # 停止 Nginx



nginx目录下的nginx.conf修改如下


//目录 nginx/nginx.conf文件
//作用 引入conf.d/*.conf所有的配置

http{
  sever{
    .....
  }

  #引入配置
  include conf.d/*.conf;
}


在nginx/conf.d文件夹创建一个demo.conf配置



//demo.conf
server {
    listen      9111;
    server_name  localhost;

    location / {
        #alias D:\\develop\\project1dir\\app\\; 
        //#配置别名到项目源代码目录,那么访问http://localhost:9111/即访问此目录

        proxy_pass http://localhost:8080/;  
        //#更聪明的做法是代理到前端服务器地址,比如gulp+browser-sync开启的服务器,能看到代码实时更新效果
        //#打开http://localhost:9111/网址,其实已代理到http://localhost:8080/了。更改代码网页会自动更新
    }

    location /config/ {
        #rewrite ^/api/(.*)$ /$1 break;   
        //#所有对后端的请求加一个api前缀方便区分,真正访问的时候移除这个前缀api


        proxy_pass http://192.168.4.124:9990;  
        //#将真正的请求代理到http://192.168.4.124:9990,即真实的服务器地址,ajax的url为/config/list的请求将会访问http://192.168.4.124:9990/config/list
    }


    location ~ .*\.(js|css|jpg|png)$ {
        #解决反向代理的路径下找不到文件,单独指定js css jpg文件的访问路径
        proxy_pass http://localhost:8080/;
    }


}