前后端分离配置Nginx实现后端负载均衡

一、环境

Windows系统、Nginx1.18.0

二、步骤

1、nginx解压根目录

D:\nginx-1.18.0

2、配置nginx.conf

文件路径:

D:\nginx-1.18.0\conf\nginx.conf

将nginx.conf内容修改为以下:

user root;
events {
    worker_connections 1024;
}

http {
    include             mime.types;
    default_type  application/octet-stream;
	add_header 'Access-Control-Allow-Origin' '*';
	add_header 'Access-Control-Allow-Headers' 'X-Requested-With';
	add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
    client_max_body_size 2000m; 
	sendfile            on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;
    include conf.d/*.conf; #项目配置在conf.d文件夹下
}

3、不同项目设置不同的配置文件

D:\nginx-1.18.0\conf目录下创建文件夹conf.d

进入D:\nginx-1.18.0\conf\conf.d目录创建demo.conf配置文件

#后端负载均衡(后端项目端口8911和8912)
upstream loadbalance {
	server 127.0.0.1:8911 max_fails=3 fail_timeout=30s weight=2;
	server 127.0.0.1:8912 max_fails=3 fail_timeout=30s weight=2;
}

server {
		#前端项目访问端口8098
        listen       8098;
        server_name  localhost;
		
		charset utf-8;
		
		location /api {

			add_header Access-Control-Allow-Origin *;
			add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
			add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

			if ($request_method = 'OPTIONS') {
				return 204;
			}
			# 前端调用接口时有/api的url都会转发到后端(loadbalance为上面upstream关键字后面的名字)
			proxy_pass http://loadbalance;

		}

        location / {
        	# 前端项目地址,D:\nginx-1.18.0根目录下的demo文件夹
            root   demo;
            index  index.html index.htm;
			try_files $uri $uri/ @router;
        }
		
		location @router {
			rewrite ^.*$ /index.html last;
		}

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
 
	}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值