前后端分离项目使用Nginx配置统一端口访问

  今天在工作中遇到一个问题:

    1.前端项目部署在服务器上怎么访问?

    2.通过Nginx代理配置前端访问路径和端口后,前端调用后端接口由于后端端口号和前端代理接口不一致导致跨域问题,怎么解决?

  针对以上问题就要配置Nginx代理,对前后端进行统一端口访问。具体配置如下:

    1.说明:我的前端放在/data/test/narcV3.1/front/drugarchives目录下, 后端访问地址为http://10.196.10.50:8213/drugHumanArchives

  在10.196.10.50服务器/usr/local/nginx/conf 下的nginx.cong中配置如下内容:

upstream drugHumanArchives { 
        server 127.0.0.1:8213 weight=1; 
    }

server {
        listen       8199;
        server_name  localhost;

    location / {
            root   /data/test/narcV3.1/front;
            index  index.html index.htm;
        }
        
        location /drugHumanArchives
        {
            proxy_set_header   Host             $host:8199;
            proxy_set_header   X-Real-IP        $remote_addr;
            proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
            proxy_cookie_path  /drugHumanArchives  /drugHumanArchives;
            proxy_set_header   Cookies          $http_cookies;
            proxy_pass http://drugHumanArchives/drugHumanArchives;
        }
}

说明:1)upstream 配置后端服务本来的访问路径

   2)server 配置代理端口  listen:统一端口号   server_name:域名   

    第一个location /   说明:访问http://10.196.10.50:8199/drugarchives   即可访问到服务器静态资源/data/test/narcV3.1/front/drugarchives /index..html

    第二个location /drugHumanArchives  说明 proxy_pass  代理路径 http://drugHumanArchives/drugHumanArchives;  第一个drugHumanArchives代表上面配置的upstream ,即http://127.0.0.1:8213/drugHumanArchives;

      访问http://10.196.10.50:8199/drugHumanArchives    即可代理到路径http://10.196.10.50:8213/drugHumanArchives

猜你喜欢

转载自www.cnblogs.com/fangyan1994/p/12202968.html