您的位置:首页 > 教育 > 锐评 > 4.nginx反向代理、负载均衡

4.nginx反向代理、负载均衡

2025/5/15 7:28:08 来源:https://blog.csdn.net/u010198709/article/details/139283556  浏览:    关键词:4.nginx反向代理、负载均衡

nginx反向代理、负载均衡

  • 一、反向代理
    • 1、语法
    • 2、注意事项
    • 3、后端服务器记录客户端真实IP
      • 3.1 在nginx反向代理时添加x-real-ip字段
      • 3.2 后端httpd修改combined日志格式
      • 3.3 后端是nginx的情况
  • 二、负载均衡 upstream模块
    • 1、负载均衡作用
    • 2、调度算法
    • 3、配置应用

一、反向代理

隐藏后端服务器地址信息

1、语法

location uri {proxy_pass 后端服务器地址;
}

需求: 将/mp3的访问请求转交到后端的/music地址

        location /mp3 {proxy_pass http://192.168.140.11/music;}

需求: 将/download请求转交到后端的/xz地址

        location /download {proxy_pass http://192.168.140.11/xz;}

2、注意事项

  • 反向代理时,nginx会将location中的uri地址自动拼接后端服务器地址
        location /first {proxy_pass http://192.168.140.11/;}
  • location中要涉及到正则匹配,后端服务器不支持写具体的uri地址
        location ~ /test {proxy_pass http://192.168.140.11;}

3、后端服务器记录客户端真实IP

3.1 在nginx反向代理时添加x-real-ip字段

        location /mp3 {proxy_pass http://192.168.140.11/music;proxy_set_header X-REAL-IP $remote_addr;}

3.2 后端httpd修改combined日志格式

[root@ca ~]# grep "LogFormat" /etc/httpd/conf/httpd.conf LogFormat "%{X-REAL-IP}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

3.3 后端是nginx的情况

proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;

修改main日志格式

$http_x_forwarded_for

二、负载均衡 upstream模块

1、负载均衡作用

流量分发,提升连接

2、调度算法

  • rr 轮询
    支持权重 weight, 高配置主机处理更多请求
    会话持久问题,利用NoSQL做会话共享

  • sh 源hash
    一段时间内,同一个客户端的请求到达同一个后端服务器
    解决会话持久问题

  • lc 最少连接

3、配置应用

// 定义后端服务器组, 支持健康状态检查
upstream 组名 {[调度算法];server IP:port weight=权重 fail_timeout=时间 max_fails=次数;server IP:port;
}// 
location uri {proxy_pass http://组名;
}
upstream webserver {server 192.168.140.11:80 weight=1 max_fails=3 fail_timeout=2;server 192.168.140.12:80 weight=1 max_fails=3 fail_timeout=2;server 127.0.0.1:8000 backup;    // backup为备份主机
}location / {proxy_pass http://webserver;proxy_set_header X-REAL-IP $remote_addr;
}
C:\Users\admin>curl 192.168.140.10
<h1> web02 </h1>C:\Users\admin>curl 192.168.140.10
<h1> web01 </h1>C:\Users\admin>curl 192.168.140.10
<h1> web02 </h1>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com