Nginx二级负载配置
前言:工作需要,为乙方做项目部署,需要使用Nginx配置二级负载,记录配置代码,以供参考。
Nginx安装
按照Nginx官网的命令进行安装,文档地址,安装完成后,配置文件默认在/etc/nginx/nginx.conf和/etc/nginx/conf.d/default.conf。
负载架构
- 一级负载,IP地址和端口为 xxx.xxx.xxx.180:9000
- 二级负载,IP地址和端口为 xxx.xxx.xxx.179:9100,在二级负载中,会再把请求根据URL分发给不同地址端口
配置文件代码
在conf.d里执行cp default.conf sw.conf,然后对sw.conf进行如下配置:
server {
listen 9000;
server_name xxx.xxx.xxx.180;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location /sw/ {
root html;
index index.html index.htm;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host:9000; #注意,server_port最好写死,否则会出问题,一级负载监听9000,那么一级和二级负载都要配置为9000,否则二级负载会拿到自己的监听端口,那是错的。
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_redirect http://$host/sw $scheme://$host/sw;
#if ($query_string ~* ^(.*)menu_id=nems(.*)$){
proxy_pass http://xxx.xxx.xxx.179:9100;
#}
}
}
配置解析:
- 先关注下面两行配置:
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
根据维基百科描述,
X-Forwarded-For的格式应该如下:
X-Forwarded-For: client1, proxy1, proxy2, ...
而nginx中,每次都是取X-Forwarded-For 中最右边的IP作为X-Real-IP的值,明显最右边的IP是一个反向代理的IP,而不是真实的客户端IP。
所以我们需要根据项目的需求来决定使用什么IP,在公司项目里,需要使用的是最外层代理的IP,所以可以直接使用上述配置。如果需要获取用户访问的真实IP,而不是代理IP,需要使用ngx_http_realip_module模块,默认这个模块没有启动,需要在安装时使用–with-http_realip_module作为configuration的参数。
- 下面是Host配置:
proxy_set_header Host $host:$server_port
Host如果不配置,拿到的就是应用的IP和端口。
经过测试发现,这个host是有传递性的,因为项目里需要获取host,所以这个配置也比较重要。假如只在二级负载配置Host,应用得到的结果是xxx.xxx.xxx.179:9100,也就是二级负载所在的服务器的ip和端口,但如果在一级负载里也配置了Host,那应用的到的结果是xxx.xxx.xxx.180:9100,会发现,端口是二级的端口,ip是一级的ip,所以在设置的时候,可以直接把server_port写死,这样就不会出现问题。
- X-Forwarded-Host、X-Forwarded-Server
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
用来确定最外层负载的ip
- X-Forwarded-Proto
proxy_set_header X-Forwarded-Proto $scheme;
用来确定客户端和一级负载之间的传输协议(http或https)