1.轮循 每个请求逐个分发到后端服务器
2.加权轮循 按照分配的权重将请求分发到后端服务器
3.ip hash 轮询的基础上,保持一个客户端多次请求分发到一台后端服务器上
一、轮询配置
#定义后端服务器组
upstream nginx-test{
server 192.168.0.128;
server 192.168.0.127;
}
server {
listen 8080;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
root "G:/phpstudy/nginx/html";
location / {
index index.html index.htm index.php l.php;
autoindex on;
proxy_pass http://nginx-test;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location ~ .php(.*)$ {
fastcgi_pass 127.0.0.1:9001;
fastcgi_index index.php;
fastcgi_split_path_info ^((?U).+.php)(/?.+)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include fastcgi_params;
}
}
二、轮询加权配置
#定义后端服务器组
upstream nginx-test{
server 192.168.0.128 weight=2;
server 192.168.0.127;
server 192.168.0.126 backup; # 备份服务器,其他服务器宕机后启动
}
server {
listen 8080;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
root "G:/phpstudy/nginx/html";
location / {
index index.html index.htm index.php l.php;
autoindex on;
proxy_pass http://nginx-test;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
三、IP Hash配置
#定义后端服务器组
upstream nginx-test{
ip_hash;
server 192.168.0.128;
server 192.168.0.127;
server 192.168.0.126;
}
server {
listen 8080;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
root "G:/phpstudy/nginx/html";
location / {
index index.html index.htm index.php l.php;
autoindex on;
proxy_pass http://nginx-test;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
四、负载均衡与反向代理区别
1、负载均衡需要通过反向代理来实现
2、反向代理就是指nginx作为前端服务器,将请求转发到后端,再将后端服务器的结果,返回给客户端
它在中间做了一个代理服务器的角色
3、负载均衡对反向代理增加了一些策略,因为后端是多台服务器,nginx会根据设定的策略将请求转发给一个相对空闲的服务器,对负载进行分流,减轻服务器压力
![9efd932e6cffee40b18261b6441d8e3a.png](https://img-blog.csdnimg.cn/img_convert/9efd932e6cffee40b18261b6441d8e3a.png)
五、反向代理配置
#定义后端服务器组
upstream nginx-test{
server 192.168.0.127;
}
server {
listen 8080;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
root "G:/phpstudy/nginx/html";
#代理配置参数
proxy_connect_timeout 180;
proxy_send_timeout 180;
proxy_read_timeout 180;
proxy_set_header Host $host;
proxy_set_header X-Forwarder-For $remote_addr;
location / {
proxy_pass http://nginx-test;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
就到这了, 以上内容希望帮助到大家,很多PHPer在进阶的时候总会遇到一些问题和瓶颈,业务代码写多了没有方向感,不知道该从那里入手去提升,对此我整理了一些资料,包括但不限于:分布式架构、高可扩展、高性能、高并发、服务器性能调优、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql优化、shell脚本、Docker、微服务、Nginx等多个知识点高级进阶干货需要的可以免费分享给大家,需要请戳这里链接 或 者关注咱们下面的知乎专栏
PHP架构师圈子zhuanlan.zhihu.com![dfac5bdf6b7f3fd01ff76d91f51180d1.png](https://img-blog.csdnimg.cn/img_convert/dfac5bdf6b7f3fd01ff76d91f51180d1.png)