nginx篇四:
nginx可以作为反向代理服务器,其中反向代理的可以是集群服务器。下面简单的介绍下作为集群服务器的配置。
1、案例分析:client一台IP地址为192.168.5.100,Nginx一台IP地址为192.168.5.1(用来接收客户端的请求)172.16.5.1(用来调度内网的服务器集群),Apache服务器两台172.16.5.2,172.16.5.3用来处理客户端的请求。
Nginx中的配置如下:
vi /etc/nginx/nginx.conf
server {
listen80;
server_namewww.hello.com;
location/{
proxy_passhttp://webservers;
proxy_set_headerX-Real-IP $remote_addr;
}
}
upstream webservers{ //upstream 不能应用在server字段里面,否则会报错。
server172.16.5.2 weight=1 max_fails=2 fail_timeout=2;
server172.16.5.3 weight=1 max_fails=2fail_timeout=2;
server127.0.0.1:8080 backup;
}
server { //作为sorry server使用,当两个提供服务的server全部宕机之后,sorryserver提供服务。
listen8080;
server_namelocalhost;
root/web/www/sorry_page;
indexindex.html index.htm;
}
2、nginx在设置反向代理的过程中,还可以实现缓存的设置。
vi /etc/nginx/nginx.conf
proxy_cache_path /nginx/cache/firstlevels=1:2 keys_zone=first:20m max_size=1g;
解释下levels的作用:
levels指的是缓存目录一共有几级目录,比如levels=1:2意思就是一共有两级目录,其中一级目录的文件名有一个字符,二级目录的文件名有两个字符。一般最多有三级目录,并且目录的文件名的字符数量不超过两个。
在location中打开缓存。
location /{
proxy_cachefirst-------àkeys_zone的名字进行引用代开。
proxy_cache off-------à表示不启用缓存。
proxy_cache_valid200 10m------à表示访问时返回值为200的缓存时间为10M,其余的参数可以根据自己的要求来进行添加。
}
需要注意的一点是:在定义缓存的目录的时候只能是先定义在使用如果是现在location中打开了缓存,但是定义的路径写在了后面。会提示错误:nginx: [emerg] the size 20971520 of shared memory zone"first" conflicts with already declared size 0 in/etc/nginx/nginx.conf:48。