环境:(全部为公网IP,可以直接和客户端通信)
分发器:192.168.200.101
静态文件服务器:192.168.200.102
192.168.200.103
动态文件服务器:192.168.200.104
192.168.200.105
图片服务器: 192.168.200.106
192.168.200.107
nginx常用的三种模式:
- 轮询 默认模式,后端服务器挂了自动踢出
- weight 指定权重
- ip_hash 每个请求按访问IP的hash结果分配,每个客户端固定访问一个后端服务器,解决session问题
安装nginx:
yum install -y gcc gcc-c++ zlib zlib-devel openssl openssl-devel pcre pcre-devel
wget http://nginx.org/download/nginx-1.12.1.tar.gz
tar xzvf nginx-1.12.1.tar.gz
cd nginx-1.12.1/
./configure --prefix=/usr/local/nginx --with-http_dav_module --with-http_stub_status_module --with-http_addition_module --with-http_sub_module --with-http_flv_module --with-http_mp4_module
make && make install
参数:
--with-http_dav_module 增加PUT,DELETE,MKCOL:创建集合,COPY和MOVE方法(默认关闭)
--with-http_stub_status_module 获得nginx上次启动以来工作状态
--with-http_addition_module 作为一个输出过滤器,支持不完全缓冲,分部分响应请求
--with-http_sub_module 允许用一些其他文本替换nginx响应中的一些文本
--with-http_flv_module flv视频支持模块
--with-http_mp4_module mp4视频支持模块
创建nginx用户
useradd nginx -s /sbin/nologin
配置动静分离
cd /usr/local/nginx/conf/
vim nginx.conf
2 user nginx;
43 location / {
44 root html;
45 index index.html index.htm;
46 if ($request_uri ~* \\.html$){
47 proxy_pass http://htmlservers;
48 }
49 if ($request_uri ~* \\.php$){
50 proxy_pass http://phpservers;
51 }
52 proxy_pass http://otherservers;
53 }
#定义负载均衡IP
124 upstream htmlservers {
125 server 192.168.200.102:80;
126 server 192.168.200.103:80;
127 }
128 upstream phpservers {
129 server 192.168.200.104:80;
130 server 192.168.200.105:80;
131 }
132 upstream otherservers {
133 server 192.168.200.106:80;
134 server 192.168.200.107:80;
135 }
nginx启动、开机自启
/usr/local/nginx/sbin/nginx
echo "/usr/local/nginx/sbin/nginx" >> /etc/rc.local
后端服务器简单配置:
htmlservers:
yum install -y httpd
htmlserver1:
echo "htmlservers 192.168.200.102" > /var/www/html/index.html
htmlserver2:
echo "htmlservers 192.168.200.103" > /var/www/html/index.html
systemctl start httpd
phpservers:
yum install -y httpd php
vim /etc/httpd/conf/httpd.conf
164 DirectoryIndex index.html index.php
phpserver1:
vim /var/www/html/index.php
<?php
echo "phpservers 192.168.200.104";
phpinfo();
?>
phpserver2:
vim /var/www/html/index.php
<?php
echo "phpservers 192.168.200.105";
phpinfo();
?>
systemctl start httpd
otherservers:
yum install -y httpd
上传两张不同图片到两台otherservers上,名称更改为a.png
systemctl start httpd
测试:
html静态页面测试:
php动态页面测试:
other其他:
缺省情况: 访问http://192.168.200.101/会打开otherservers