nginx反向代理、负载均衡
一、反向代理
隐藏后端服务器地址信息
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>