一、本地环境

1.1本地后端

应用上下文 api
在这里插入图片描述

测试接口

curl --request GET \
  --url http://localhost:8080/api/captchaImage

后端应用返回
在这里插入图片描述

1.2本地前端

前端代理后端接口,对应后端的ip+端口+应用上下文
在这里插入图片描述

配置前端路由
在这里插入图片描述

配置前端路由在这里插入图片描述

二、测试环境

2.1 测试后端

第一步
测试环境,在应用服务器上,测试

curl --request GET \
  --url http://localhost:8080/api/captchaImage

应用返回结果
在这里插入图片描述
第二步
配置nginx应用后端

 		#ruoyi后端应用
 		location /api {
                proxy_pass  http://localhost:8080/api;
        }

配置完nginx,检测公网是否可以通过nginx访问
(公网ip+nginx监听端口+nginx配置文件中拦截路由,对应location后面的api)

curl --request GET --url http://106.54.220.184:80/api/captchaImage

应用返回
在这里插入图片描述

2.2 测试前端80端口直接访问

配置ip+80端口直接访问到

http://106.54.220.184

修改前端项目
在这里插入图片描述在这里插入图片描述

npm run build:stage

部署
在这里插入图片描述

nginx配置http默认走80,所以配置到80下面

    	# 默认访问
        # 部署路径:/app/nginx/html/dist-g
        # 访问路径为:http://localhost:80
        location / {
            try_files $uri $uri/ /index.html;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Host $http_host;
            root /app/nginx/html/dist-g;
            index index.html index.htm;
        }

在这里插入图片描述

配置完成
在这里插入图片描述
在这里插入图片描述

2.3 测试前端路由前缀访问

配置ip+端口+路由访问(ruoyi

http://106.54.220.184/ruoyi

修改前端项目
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

npm run build:stage

部署
在这里插入图片描述
修改Nginx配置,并重新加载配置

      	# 带前缀的访问
        # 部署路径:/app/nginx/html/dist-r
        # 访问路径为:http://localhost:80/ruoyi
        location /ruoyi {
            try_files $uri $uri/ /index.html;
            alias /app/nginx/html/dist-r;
            index index.html index.htm;
        }

测试
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三、Nginx容器部署前后端分离

因为nginx是使用docker启动,所以文件目录需要更改,宿主机/app/nginx 映射容器内部/usr/share/nginx

        # 默认访问
        # 部署路径:/app/nginx/html/dist-g
        # 访问路径为:http://localhost:80
        location / {
            try_files $uri $uri/ /index.html;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Host $http_host;
            root /usr/share/nginx/html/dist-g;
            index index.html index.htm;
        }

容器内要访问宿主机服务,需要查看docker0的网络

ip addr show docker0

查询结果docker0:172.17.0.1

        #ruoyi后端应用
        location /api {
             proxy_pass http://172.17.0.1:8080/api;
        }

四、root与alias

1.root

指定静态资源目录位置,它可以写在 http 、 server 、 location 等配置中。

配置:location /image { root /opt/nginx/static;}

当用户访问 www.test.com/image/1.png 时,实际在服务器找的路径是 /opt/nginx/static/image/1.png

[注意] root 会将定义路径与 URI 叠加, alias 则只取定义路径。

2.alias

它也是指定静态资源目录位置,它只能写在 location 中。

配置:location /image { alias /opt/nginx/static/image/;}

当用户访问 www.test.com/image/1.png 时,实际在服务器找的路径是 /opt/nginx/static/image/1.png

[注意] 使用 alias 末尾一定要添加/,并且它只能位于 location 中。

Logo

快速构建 Web 应用程序

更多推荐