NGINX
- 一、准备
 - 二、配置NGINX服务器
 - 
- [1. 下载NGINX](#1. 下载NGINX)
 - [2. 编写配置文件](#2. 编写配置文件)
 - [3. 启动NGINX服务](#3. 启动NGINX服务)
 
 - 三、配置后端服务
 - 四、测试
 
一、准备
- 准备5台CentOS7服务器,IP地址如下:
- HAproxy 192.168.152.71
 - web1 192.168.152.72
 - web2 192.168.152.73
 - php1 192.168.152.74
 - php2 192.168.152.75
 
 
二、配置NGINX服务器
1. 下载NGINX
            
            
              bash
              
              
            
          
          yum install -y nginx
        2. 编写配置文件
            
            
              bash
              
              
            
          
          vim /etc/nginx/nginx.conf
        编写内容如下:
- 
在 http 块中
bash# 定义处理 .html 文件的上游服务器组 upstream htmlservers { # 权重 1 (可选,默认 1),失败 2 次后标记为不可用(可选,默认 1),故障检测时间为 10 秒(可选,默认 10 秒) server 192.168.152.72:80 weight=1 max_fails=2 fail_timeout=2; # 权重 2 (可选,默认 1),失败 2 次后标记为不可用(可选,默认 1),故障检测时间为 10 秒(可选,默认 10 秒) server 192.168.152.73:80 weight=2 max_fails=2 fail_timeout=2; } # 定义处理 .php 文件的上游服务器组 upstream phpservers { # 权重 1 (可选,默认 1),失败 2 次后标记为不可用(可选,默认 1),故障检测时间为 10 秒(可选,默认 10 秒) server 192.168.152.74:80 weight=1 max_fails=2 fail_timeout=2; # 权重 2 (可选,默认 1),失败 2 次后标记为不可用(可选,默认 1),故障检测时间为 10 秒(可选,默认 10 秒) server 192.168.152.75:80 weight=2 max_fails=2 fail_timeout=2; } - 
在server块中
bash# 匹配所有请求,默认请求,没有定义的请求全部走这个服务器 location / { proxy_pass http://htmlservers; } # 对所有以 .html 结尾的请求进行处理 location ~* \.html$ { # 将请求转发到 htmlservers 服务器组 proxy_pass http://htmlservers; } # 对所有以 .php 结尾的请求进行处理 location ~* \.php$ { # 将请求转发到 phpservers 服务器组 proxy_pass http://phpservers; } - 
关于权重
weight- 权重相同时采用 轮询算法:请求会按顺序依次分配到服务器组中的每台服务器。
 - 权重不同时采用 加权轮询算法:根据各个服务器的权重值来分配请求。权重越高的服务器会处理更多的请求。
 
 
3. 启动NGINX服务
            
            
              bash
              
              
            
          
          systemctl start nginx && systemctl enable nginx
        三、配置后端服务
①配置web服务器
测试用简单配置,web1 和 web2 都要配置
- 
安装http服务
bashyum install -y httpd - 
编写主页
web1:bashecho web1 > /var/www/html/index.htmlweb2:
bashecho web2 > /var/www/html/index.html - 
启动http服务
bashsystemctl start httpd && systemctl enable httpd 
②配置php服务器
测试用简单配置,php1 和 php2 都要配置
- 
安装 php 和 http 服务
bashyum install -y httpd php - 
编写主页
php1:bashecho php1 > /var/www/html/index.phpphp2:
bashecho php2 > /var/www/html/index.php - 
启动服务
bashsystemctl start httpd && systemctl enable httpd 
四、测试
多次刷新,查看结果,前两个的结果为 web1,web2;最后一个结果为 php1,php2。
如果配置没有问题,但多次刷新无果,可能是浏览器缓存,可以用命令 elinks
下载 yum insdall -y elinks
            
            
              bash
              
              
            
          
          elinks --dump http://192.168.152.71
elinks --dump http://192.168.152.71/index.html
elinks --dump http://192.168.152.71/index.php