nginx根据域名二级目录进行转发实现负载均衡
Posted timelessmemoryli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nginx根据域名二级目录进行转发实现负载均衡相关的知识,希望对你有一定的参考价值。
目前需求如下 只有一个域名 要求根据不同的路径转发到不同服务器
实现如下(本地)
worker_processes 1;
events
worker_connections 1024;
http
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
#81~83端口 模拟web服务器集群
server
listen 81;
server_name 127.0.0.1;
location /
root html;
index 81.html;
server
listen 82;
server_name 127.0.0.1;
location /
root html;
index 82.html;
server
listen 83;
server_name 127.0.0.1;
location /
root html;
index 83.html;
#单独服务器专用于处理websocket请求
server
listen 86;
server_name 127.0.0.1;
location /
root html;
index schoolA_websocket.html;
#根据ip策略负载web服务器
upstream shcoolA_http_io_nodes
ip_hash;
server 127.0.0.1:81;
server 127.0.0.1:82;
server 127.0.0.1:83;
upstream shcoolA_websocket_io_nodes
server 127.0.0.1:86;
#主入口
server
listen 80;
server_name 127.0.0.1;
#location ^~ /http/schoolA 表示以http/schoolA开头,下面的是精确匹配
location /http/schoolA
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_http_version 1.1;
proxy_pass http://shcoolA_http_io_nodes/;#最后斜杠决定转发之后的路径
#location ^~ /websocket/schoolA
location /websocket/schoolA
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_http_version 1.1;
proxy_pass http://shcoolA_websocket_io_nodes/;
location /
return 403;
关于proxy_pass最后斜杠的补充说明
如果proxy_pass 的URL以 / 结尾 ,那么请求转发的时候将不会带上匹配到的 /http/schoolA ,也就是说如果请求 URL是 127.0.0.1:80/http/schoolA/login,nginx将会把这个请求转发成 127.0.0.1:81/login,反之则是127.0.0.1:81/http/schoolA/login
以上是关于nginx根据域名二级目录进行转发实现负载均衡的主要内容,如果未能解决你的问题,请参考以下文章