在线教育项目-Nginx配置文件-请求转发

conf/nginx.conf

#user  nobody;
worker_processes  1;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       81;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
    server {
        listen 9001;
        server_name localhost;
        location ~ /eduservice/ {           
            proxy_pass http://localhost:8001;
        }
        location ~ /eduoss/ {   
            proxy_pass http://localhost:8002;
        }
    }
}

监听端口 9001,名称 localhost,将 /eduservice/ 下的请求转发到 http://localhost:8001。

就比方说,我后端写的一个sql查询语句,返回一些数据要在前端显示。

@RestController//交给Spring管理,返回json数据
@RequestMapping("/eduservice/teacher")
@CrossOrigin//解决跨域问题
public class EduTeacherController {
    ......
    @GetMapping("findAll")
    public R findAllTeacher() {
        //调用service的方法实现查询所有的操作
        List<EduTeacher> list = teacherService.list(null);
        return R.ok().data("items", list);
    }
    ......
}

它所在模块设置的服务端口是8001,那么它的真实访问地址是:http://localhost:8001/eduservice/teacher/findAll
这里的返回数据是封装过的,采用的链式编程,我在之前的博客中提到过,在这里不重要。在这里插入图片描述

启动 nginx.exe 后
我们用9001端口去访问的效果
在这里插入图片描述
可以看到效果是一样的,它是通过 eduservice 知道去访问8001端口,而不是8002。

当我们服务模块多起来后,会开放许多服务端口,而前端对后端的访问只需要通过 9001 这个监听端口就好了。
而且前端是看不到实际端口号的,web服务器就更加神秘了。

猜你喜欢

转载自blog.csdn.net/weixin_43845524/article/details/106727353