需求
业务场景中常遇到需要同时部署多个前端服务的情况,此时需借助Nginx进行统一管理和路由分发。
Nginx多个前端服务配置方式
针对多前端服务的部署需求,通常可采用两种主流配置策略:一是利用单个Server块内的多个Location指令进行区分;二是为每个服务独立配置一个Server块。
多个location配置
location中root和alias的区别:location后面的路径是真实路径用root,虚拟路径用alias
真实路径就是本地访问地址里面有的路径
例如vue前端服务设置了publicPath='/allow-cost-calc',
前端访问路径为:http://localhost:8005/allow-cost-calc/#/login,/allow-cost-calc就是真实路径,则使用 location /allow-cost-calc配置时里面使用root 来指定前端服务路径(如下服务3配置)。
如果前端应用的访问路径简化为root形式(如http://localhost:8005/#/login),且配置中仍使用/指令,那么location后跟随的必须是真实的文件系统路径,此时只能使用/作为根路径。然而,在多服务共存环境中,根路径alias可能已被其他服务占用(如服务1已使用该路径)。为解决此冲突,可引入虚拟路径概念:例如定义作为虚拟路径前缀,并使用指令指向具体的服务目录。部署完成后,用户访问时需包含该虚拟路径,即http://localhost:8005/s2/#/login(参考服务2的配置示例)。
http {
#嵌入其他配置文件 语法:include /path/file
#参数既可以是绝对路径也可以是相对路径(相对于Nginx的配置目录,即nginx.conf所在的目录)
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
#限制上传文件大小
client_max_body_size 20m;
server {
client_max_body_size 100M;
listen 1004;
server_name localhost, 127.0.0.1;
#服务1
location / {
root dist;
index index.html;
}
#服务2:由于/r2 是虚拟路径,所以用alias,会为访问dist3下面的首页
location /r2 {
alias dist3;
#服务3:由于/allow-cost-calc 是真实路径,所以用root,会访问/allow-cost-calc/dist2下面的首页
#(vue打包时设置了publicPath = '/allow-cost-calc',同时打包后的文件也必须放到allow-cost-calc文件夹下 dists2/allow-cost-calc/前端包文件)
location /allow-cost-calc {
root dist2;
#后端代理,后端代理不受前端路径的影响
location /api/ {
proxy_pass http://10.51.105.7:31500/;
proxy_pass_request_headers on;
proxy_set_header Host $host;
proxy_set_header X-Client-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
多个server配置
另一种方案是为每个前端服务分配独立的Server块,实现完全隔离。以下是nginx.conf的部分配置示例:
http {
#前端服务1
server {
root dist1;#前端包位置
client_max_body_size 100M;
listen 7001;
server_name localhost, 127.0.0.1;
location /api/ {
proxy_pass http://10.51.105.7:31500/;
proxy_pass_request_headers on;
proxy_set_header Host $host;
proxy_set_header X-Client-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
#前端服务2
root dist2;#前端包位置
listen 7002;
}
以上介绍了Nginx部署多个前端服务的两种配置方法及相关注意事项。如需了解更多Nginx多前端配置细节,建议查阅本站历史文章或继续浏览后续内容,感谢支持。