集成内容:nginx + Vue打包 + spring boot

一.反向代理配置

80端口转发到9500端口

1
2
3
4
5
listen       80;
server_name localhost:9500;
location / {
proxy_pass http://localhost:9500; #如果只是基本的转发,没有前后端容器的分别就直接配置proxy_pass就行了
}

二.nginx来进行静态文件伺服 (前后端分离)

1
2
3
4
5
6
7
8
9
listen       80;  
server_name localhost:9500;
location / { #先配置静态资源的路径
root E:/dist/;
index index.html;
}
location ~/(a|user)/ { # 配置服务器请求路径转发(使用正则表达式,匹配a或者user开头的路径)
proxy_pass http://localhost:9500;
}

nginx 可以作为前端的容器。什么是容器?为什么前端也需容器?
从字面意思看,容器肯定是用来放东西的,就像通常产品都需要包装才能卖出去一样,容器为软件产品的运行提供了环境(条件支持),没有容器,产品就不能运行,如把tomcat称作是servlet的容器,意味着tomcat为servlet提供了运行环境。那nginx可作为前端的容器,意味着nginx为前端页面的访问展示提供了环境(支持),镜像一个静态html文件放在服务器上之后,没有这些容器的支持,你无法访问这个文件一样的道理。

三.nginx 配置负载均衡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
upstream myserver {  
server localhost:9500 weight=1; #引入权重的概念
server localhost:9501 weight=5;
}

server {
listen 80;
server_name localhost:9500;

location /{
root E:/dist/;
index index.html;
}

location ~/(a|user)/ {
proxy_pass http://myserver; #这里的名称带下划线会出错
}
}

四.常见问题

1.多台机器间session的共享问题

不使用session,换作cookie

2.nginx + vue包 刷新 404 not fund

https://blog.csdn.net/xu622/article/details/87348848

1
2
3
4
5
location / {
root /mydata/transfer/html/helper/dist;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}

在配置中加上try_files,意思跟翻译差不多,“尝试读取文件”。uri这个是nginx的一个变量,存放着用户访问的地址,例如http://localhost:8200/chooseSize那么 uri 这个是nginx的一个变量,存放着用户访问的地址,例如http://localhost:8200/chooseSize 那么uri这个是nginx的一个变量,存放着用户访问的地址,例如http://localhost:8200/chooseSize那么uri就是/chooseSize;uri/代表访问的是一个目录例如http://localhost:8200/chooseSize/那么 uri/ 代表访问的是一个目录 例如http://localhost:8200/chooseSize/ 那么uri/代表访问的是一个目录例如http://localhost:8200/chooseSize/那么uri/就是/chooseSize/;最后/index.html就是我们首页的地址。
最终上面的意思是如果第一个存在,直接返回;不存在的话读取第二个,如果存在,读取返回;如果还是不存在,就会fall back到 try_files 的最后一个选项 /index.html,发起一个内部 “子请求”,也就是相当于 nginx 发起一个 HTTP 请求到 http://localhost:8200/index.html,再通过前端路由到/chooseSize。

3.nginx 请求超时设置

配置proxy_read_timeout 属性呢

1
2
3
4
     location ~/(a|user)/ {
proxy_pass http://myserver;
proxy_read_timeout 1500; # 秒
}

如果nginx作为前端的容器,同时前端做了请求超时限制,那么实际限制时间=min(限制时间)

4.负载均衡分配方式

ip_hash 每个请求按访问ip的hash结果分配,

轮询 每个请求按时间顺序逐一分配到不同的后端服务器,

五.常用命令

nginx -s reload

nginx -t //检查配置文件

六.概念解读

1.正向代理和反向代理

proxy和client 在同一lan,代理客户端访问服务器,这就是正向代理

proxy和server在同一lan,代理服务器接收客户机的请求,这就是反向代理,反向代理通常有很多server