nginx代理域名二级目录到前端IP+port,代码服务器nginx代理实现前后端分离

已有域名:https://for.example.com/

 

打算用二级域名:https://for.example.com/abc作为项目用。

代码服务器IP:192.168.101.1

- 前端:192.168.101.1:10080

- 后端:192.168.101.1:8006

 

1. 已有域名分配二级目录abc(最好是前端开发api路径)给需要代理的IP+port:

        location ^~ /abc/ {
            add_header 'Access-Control-Allow-Origin' *;
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
            proxy_pass http://192.168.101.1:10080;
            set $Real $proxy_add_x_forwarded_for;
            if ( $Real ~ (\d+)\.(\d+)\.(\d+)\.(\d+),(.*) ){
                set $Real $1.$2.$3.$4;
            }
        }

 此时,发送到https://for.example.com/abc的请求就代理到http://192.168.101.1:10080,注意前端发的所有请求都必须加上abc,比如二次请求:https://for.example.com/abc/secondrequest

具体nginx信息可以查看access.log

2. 代码服务器nginx代理,实现前后端分离:

[root@localhost vhost]# cat abc_nginx.conf
server
    {
        listen 10080;
        server_name _;
        index index.html;
        root  /home/wwwroot/default;

        location ~^/abc/#/home {
            root /home/wwwroot/default;
        }

        location /abc/(.*)
        {
            proxy_pass http://localhost:8006/$1;
        }

        access_log  /home/wwwlogs/access.log;
    }

 

posted @ 2021-02-28 10:54  loorean  阅读(621)  评论(0)    收藏  举报