前言

最近正在开发项目,即用到了Java的Spring Boot,又用到了Python的Flask,为了保证在同一域名下访问,我使用了Nginx做反向代理,只代理一个还比较好配置,代理的多了各种接口疯狂报错。为了防止以后再踩坑,写下这篇博客来记录最正确的配置。

第一个代理

主应用接口

使用SpringBoot开发的应用,指向域名的根目录,代理地址http://127.0.0.1:9000

1
2
3
4
5
6
7
8
9
10
11
12
13
14
location /
{
proxy_pass http://127.0.0.1:9000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header REMOTE-HOST $remote_addr;

add_header X-Cache $upstream_cache_status;

#Set Nginx Cache

add_header Cache-Control no-cache;
}

静态文件

如果只有一个应用的话可以这样写,只会代理如下格式文件。

1
2
3
4
5
6
7
8
9
location ~* \.(gif|png|jpg|css|js|woff|woff2)$
{
proxy_pass http://127.0.0.1:9000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header REMOTE-HOST $remote_addr;
expires 12h;
}

第二个代理

后端接口

这个是使用Flask开发的应用,指向/query目录,代理地址http://127.0.0.1:9099

1
2
3
4
5
6
7
8
9
10
11
12
13
14
location ^~ /query
{
proxy_pass http://127.0.0.1:9099;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header REMOTE-HOST $remote_addr;

add_header X-Cache $upstream_cache_status;

#Set Nginx Cache

add_header Cache-Control no-cache;
}

前面的^~一定要写,不然它只能指向代理地址的第一层路径,剩下其他的就全执行不了了。

前端目录

这个没有什么好说的,设定好目录之后会自动指向index文件。

1
2
3
4
location /app
{
alias /www/your-path/app;
}

你要硬说有坑的话,那就参见alias和root区别

前端静态文件

虽然前面已经引用过根目录了,但是static目录并没有被引用,访问的话会直接指向第一个代理程序,所以我们还需要再引用一次。

1
2
3
4
location ^~ /app/static/
{
alias /www/your-path/app/assets/;
}

前面的^~一定要写,不然访问文件疯狂404。

第三种写法

前两种写法虽然能用,但是写了两个总感觉有些多余,本身前端静态文件和静待文件就是在一起的,我们把它合并成一个。

1
2
3
4
location ^~ /app/
{
alias /www/your-path/app/;
}

指定目录后面加上/就可以直接引导到整个文件夹。

负载均衡

负载地址

如果你怕一个服务宕机,想拥有更稳定的服务,你可以同时在两个服务器上部署应用,然后使用Nginx做负载均衡。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
upstream fzjh 
{
server 127.0.0.1:5000 weight=2;
server 127.0.0.1:5000 weight=1;
}
location /
{
proxy_pass http://fzjh;
proxy_set_header Host zxwS;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header REMOTE-HOST $remote_addr;

add_header X-Cache $upstream_cache_status;

#Set Nginx Cache

add_header Cache-Control no-cache;
}

weight代表权重,理论上权重越高,被分配到该服务器的几率越大。

静态文件

在Nginx服务器上存储一份静态资源,使用下面这行代码引导。

1
2
3
4
location  ~* \.(gif|png|jpg|css|js|woff|woff2)$
{
root /www/your-path/static;
}

alias和root区别

alias

1
2
3
4
location /static/
{
alias /www/your-path/static/;
}

此时Nginx会自动去/www/your-path/static/目录找文件

root

1
2
3
4
location /static/
{
root /www/your-path/static/;
}

此时Nginx会自动去/www/your-path/static/static/目录找文件,等于说多了一层