nginx负载均衡,配置动静分离
nginx反向代理
nginx是一种高性能的Web服务器和反向代理服务器,它可以用作反向代理的工具。反向代理是指将客户端的请求转发到后端的多个服务器上,然后将后端服务器的响应返回给客户端。通过反向代理,可以实现负载均衡、缓存加速、SSL 终端、安全过滤等功能。
nginx负载均衡
nginx可以用作负载均衡。负载均衡是指将客户端的请求均匀地分配到多个后端服务器上,以实现服务器资源的充分利用和提高网站的性能和可靠性。常见的负载均衡算法有轮询、IP 哈希、最少连接等。
什么是动静分离
动静分离是让动态网站里的动态网页根据一定规则把不变的资源和经常变的资源区分开来,动静资源做好了拆分以后,我们就可以根据静态资源的特点将其做缓存操作,这就是网站静态化处理的核心思路。
proxy模块和upstream模块功能
http proxy模块功能很多,最常用的是proxy_pass和proxy_cache
如果要使用proxy_cache,需要集成第三方的ngx_cache_purge模块,用来清除指定的URL缓存。这个集成需要在安装nginx的时候去做,如:
./configure --add-module=../ngx_cache_purge-1.0 ......
nginx通过upstream模块来实现简单的负载均衡,upstream需要定义在http段内
在upstream段内,定义一个服务器列表,默认的方式是轮询,如果要确定同一个访问者发出的请求总是由同一个后端服务器来处理,可以设置ip_hash,如:
upstream idfsoft.com {
ip_hash;
server 127.0.0.1:9080 weight=5;
server 127.0.0.1:8080 weight=5;
server 127.0.0.1:1111;
}
注意:这个方法本质还是轮询,而且由于客户端的ip可能是不断变化的,比如动态ip,代理,翻墙等,因此ip_hash并不能完全保证同一个客户端总是由同一个服务器来处理。
定义好upstream后,需要在server段内添加如下内容:
server {
location / {
proxy_pass http://idfsoft.com;
}
}
环境准备:
主机名 | ip地址 | 环境说明 |
---|---|---|
nginx | 192.168.200.10 | 部署nginx |
lnmp | 192.168.200.20 | 部署lnmp |
lb | 192.168.200.40 | 部署nginx |
lb主机做nginx负载均衡
部署lnmp和nginx
lnmp和nginx的部署请参考:lnmp部署-CSDN博客
nginx负载均衡配置
编辑nginx.conf配置文件,添加虚拟主机
[root@nginx ~]# cd /usr/local/nginx/conf/
[root@nginx conf]# vi nginx.conf
...
server {
listen 8080;
server_name www.tanggxin.com;
access_log /var/log/nginx/www.tanggxin.com.access.log main;
location / {
root /usr/local/nginx/html/www.tanggxin.com;
index index.html index.htm;
}
}
...
[root@nginx conf]#
创建域名目录添加一个静态页面,重启nginx服务
[root@nginx conf]# mkdir /usr/local/nginx/html/www.tanggxin.com
[root@nginx conf]#
[root@nginx conf]# echo "hello world" > /usr/local/nginx/html/www.tanggxin.com/index.html
[root@nginx conf]#
[root@nginx conf]# cat /usr/local/nginx/html/www.tanggxin.com/index.html
hello world
[root@nginx conf]#
[root@nginx conf]# systemctl restart nginx
[root@nginx conf]#
[root@nginx conf]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:8080 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
[root@nginx conf]#
访问网页
实现动静分离
[root@lb ~]# cd /usr/local/nginx/conf/
[root@lb conf]# vi nginx.conf
...
upstream dynamic {
server 192.168.200.20:80 weight=1;
}
upstream static {
server 192.168.200.10:80 weight=1;
server 192.168.200.10:8080 weight=1;
}
...
location / {
proxy_pass http://static;
}
...
location ~ \.php$ {
proxy_pass http://dynamic;
}
...
[root@lb conf]# systemctl restart nginx
[root@lb conf]#
[root@lb conf]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
[root@lb conf]#
使用负载均衡主机的ip地址访问静态资源和动态资源
访问静态资源
访问动态资源