欢迎来到代码驿站!

Nginx

当前位置:首页 > 服务器 > Nginx

Nginx多个前端服务配置方式详解

时间:2022-09-28 09:39:40|栏目:Nginx|点击:

需求

有多个前端服务需要通过Nginx部署。

Nginx多个前端服务配置方式

可以通过多个server配置或者多个location配置来配置多个前端服务。

多个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配置)。

若前端访问路径为:http://localhost:8005/#/login,如果此时我们使用root来配置,那么location后面的路径只能使用真实路径,只能使用 /,但是多个服务配置时/有可能已被使用(例如下面被服务1配置了),所以需要使用虚拟路径来配置,如下服务2配置:使用/s2 来作为虚拟路径,使用alias来指定服务位置,部署后的访问方式要带上虚拟路径http://localhost:8005/s2/#/login

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;
}

上一篇:k8s部署ingress-nginx的方法步骤

栏    目:Nginx

下一篇:没有了

本文标题:Nginx多个前端服务配置方式详解

本文地址:http://www.codeinn.net/misctech/214921.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有