1、Nginx 反向代理负载均衡页面缓存URL重写及读写分离详解大纲一、前言二、环境准备三、安装与配置Nginx四、Nginx之反向代理五、Nginx之负载均衡六、Nginx之页面缓存七、Nginx之URL重写八、Nginx之读写分离注:操作系统为CentOS 6.5 x84_64,Nginx是最新版1.4.4一、前言 在前面的几篇博文中我们主要讲解了Nginx作为Web服务器知识点,主要的知识点有nginx的理论详解、nginx作为web服务器的操作讲解、nginx作为LNMP架构的讲解,不清楚的博友可以回头看看,在这一篇博客中我们主要讲解, nginx的反向代理、负载均衡、缓存、URL重写以及
2、读写分离详解。好了,下面我们来具体说一说。二、环境准备1.操作系统:CentOS 6.5 x84_642.软件:Nginx 1.4.44.安装源:rootlocalhost nginx# rpm -ivh http:/download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpmrootweb1 # rpm -ivh http:/download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm5各节点时间同步(rootnginx )#
3、 ntpdate 202.120.2.101 (rootweb1 )# ntpdate 202.120.2.101 (rootweb2 )# ntpdate 202.120.2.1016.关闭防火墙与selinux#service iptables stop chkconfig iptables off getenforce 三安装Nginx1.解压rootlocalhost nginx#tar -zxvf nginx-1.4.4.tar.gz2.新建nginx用户与组rootlocalhost nginx# groupadd -g 108 -r nginxrootlocalhost ngin
4、x#useradd -u 108 -r -g 108 nginxrootlocalhost nginx#id nginx3.准备编译配置文件rootlocalhost nginx#yum -y install pcre-devel openssl-develrootlocalhost nginx-1.4.4#./configure -prefix=/usr/ -sbin-path=/usr/sbin/nginx -conf-path=/etc/nginx.conf -error-log-path=/var/log/nginx/error.log -http-log-path=/var/log/
5、nginx/access.log -pid-path=/var/run/nginx/nginx.pid -lock-path=/var/lock/nginx.lock -user=nginx -with-http_ssl_module -with-http_flv_module -with-http_stub_status_module -with-http_gzip_static_module -http-client-body-temp-path=/var/tmp/nginx/client/ -http-proxy-temp-path=/var/tmp/nginx/proxy/ -http
6、-fastcgi-temp-path=/var/tmp/nginx/fcgi/ -http-uwsgi-temp-path=/var/tmp/nginx/uwsgi -http-scgi-temp-path=/var/tmp/nginx/scgi -with-pcre4.编译安装rootlocalhost nginx-1.4.4# make & make install5.为nginx提供SysV init 脚本rootlocalhost nginx-1.4.4# cat /etc/init.d/nginx #!/bin/sh # # nginx - this script starts an
7、d stops the nginx daemon # # chkconfig: - 85 15 # description: Nginx is an HTTP(S) server, HTTP(S) reverse # proxy and IMAP/POP3 proxy server # processname: nginx # config: /etc/nginx/nginx.conf # config: /etc/sysconfig/nginx # pidfile: /var/run/nginx.pid # Source function library. . /etc/rc.d/init.
8、d/functions # Source networking configuration. . /etc/sysconfig/network # Check that networking is up. $NETWORKING = no & exit 0 nginx=/usr/sbin/nginx prog=$(basename $nginx) NGINX_CONF_FILE=/etc/nginx/nginx.conf -f /etc/sysconfig/nginx & . /etc/sysconfig/nginx lockfile=/var/lock/subsys/nginx make_d
9、irs() # make required directories user=nginx -V 2&1 | grep configure arguments: | sed s/*-user=( *).*/1/g - options=$nginx -V 2&1 | grep configure arguments: for opt in $options; do if echo $opt | grep .*-temp-path ; then value=echo $opt | cut -d = -f 2 if ! -d $value ; then # echo creating $value m
10、kdir -p $value & chown -R $user $value fi fi done start() -x $nginx | exit 5 -f $NGINX_CONF_FILE | exit 6 make_dirs echo -n $Starting $prog: daemon $nginx -c $NGINX_CONF_FILE retval=$? echo $retval -eq 0 & touch $lockfile return $retval stop() echo -n $Stopping $prog: killproc $prog -QUIT retval=$?
11、echo $retval -eq 0 & rm -f $lockfile return $retval restart() configtest | return $? stop sleep 1 start reload() configtest | return $? echo -n $Reloading $prog: killproc $nginx -HUP RETVAL=$? echo force_reload() restart configtest() $nginx -t -c $NGINX_CONF_FILE rh_status() status $prog rh_status_q
12、() rh_status /dev/null 2&1 case $1 in start) rh_status_q & exit 0 $1 ; stop) rh_status_q | exit 0 $1 ; restart|configtest) $1 ; reload) rh_status_q | exit 7 $1 ; force-reload) force_reload ; status) rh_status ; condrestart|try-restart) rh_status_q | exit 0 ; *) echo $Usage: $0 start|stop|status|rest
13、art|condrestart|try-restart|reload|force-reload|configtest exit 2 esac6.为此脚本赋予执行权限rootlocalhost # chmod +x /etc/init.d/nginx7.添加至服务管理列表,并让其开机启动rootlocalhost #chkconfig -add nginxrootlocalhost #chkconfig -list | grep nginxrootlocalhost #chkconfig nginx on8.启动nginxrootlocalhost #service nginx start9.查
14、看一下端口rootlocalhost #netstat -ntlp |grep 8010.测试一下四Nginx之反向代理在配置nginx反向代理之间我们得先准备两台测试服务器,web1与web21.安装httpdrootweb1 #yum y install httpdrootweb2 # yum y install httpd2.提供测试页面rootweb1 # echo “” /var/www/html/index.htmlrootweb2 # echo “” /var/www/html/index.html3.启动httpd服务rootweb2 # service httpd resta
15、rt rootweb1 # service httpd restart 4.测试一下5.简单说一下,正向代理与反向代理(1).正向代理的概念 正向代理,也就是传说中的代理,他的工作原理就像一个跳板,简单的说,我是一个用户,我访问不了某网站,但是我能访问一个代理服务器,这个代理服务器呢,他能访问那个我不能访问的网站,于是我先连上代理服务器,告诉他我需要那个无法访问网站的内容,代理服务器去取回来,然后返回给我。从网站的角度,只在代理服务器来取内容的时候有一次记录,有时候并不知道是用户的请求,也隐藏了用户的资料,这取决于代理告不告诉网站。 结论就是,正向代理 是一个位于客户端和原始服务器(origi
16、n server)之间的服务器,为了从原始服务器取得内容,客户端向代理发送一个请求并指定目标(原始服务器),然后代理向原始服务器转交请求并将获得的内容返回给客户端。客户端必须要进行一些特别的设置才能使用正向代理。(2).反向代理的概念继续举例: 例用户访问 这个域名对应的服务器就设置了反向代理功能。 结论就是,反向代理正好相反,对于客户端而言它就像是原始服务器,并且客户端不需要进行任何特别的设置。客户端向反向代理的命名空间(name-space)中的内容发送普通请求,接着反向代理将判断向何处(原始服务器)转交请求,并将获得的内容返回给客户端,就像这些内容原本就是它自己的一样。(3).两者区别从
17、用途上来讲: 正向代理的典型用途是为在防火墙内的局域网客户端提供访问Internet的途径。正向代理还可以使用缓冲特性减少网络使用率。反向代理的典型用途是将防火墙后面的服务器提供给Internet用户访问。反向代理还可以为后端的多台服务器提供负载平衡,或为后端较慢的服务器提供缓冲服务。另外,反向代理还可以启用高级URL策略和管理技术,从而使处于不同web服务器系统的web页面同时存在于同一个URL空间下。从安全性来讲: 正向代理允许客户端通过它访问任意网站并且隐藏客户端自身,因此你必须采取安全措施以确保仅为经过授权的客户端提供服务。反向代理对外都是透明的,访问者并不知道自己访问的是一个代理。6
18、.nginx 代理模块说明:代理模块的指令有很多我这里只讲解重要的proxy_pass,想了解更多代理指令请参考官方中文文档。这个模块可以转发请求到其他的服务器。HTTP/1.0无法使用keepalive(后端服务器将为每个请求创建并且删除连接)。nginx为浏览器发送HTTP/1.1并为后端服务器发送HTTP/1.0,这样浏览器就可以为浏览器处理keepalive。 如下例:location / proxy_pass http:/localhost:8000; proxy_set_header X-Real-IP $remote_addr;注意,当使用http proxy模块(甚至FastC
19、GI),所有的连接请求在发送到后端服务器之前nginx将缓存它们,因此,在测量从后端传送的数据时,它的进度显示可能不正确实验拓补图:7.配置http反向代理rootnginx # cd /etc/nginx/rootnginx nginx# cp nginx.conf nginx.conf.bak #备份一个原配置文件rootnginx nginx# vim nginx.conflocation / proxy_pass http:/192.168.18.201; 指令说明:proxy_pass语法:proxy_pass URL默认值:no 使用字段:location, location中的i
20、f字段 这个指令设置被代理服务器的地址和被映射的URI,地址可以使用主机名或IP加端口号的形式,例如:proxy_pass http:/localhost:8000/uri/;8.重新加载一下配置文件rootnginx # service nginx reloadnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful重新载入 nginx: 确定9.测试一下大家可以看到,当我们访问192.16
21、8.18.208时,被代理重新定向到Web1上10.查看一下Web服务器日志略。我们修改一下,让日志的IP显示真实的客户端的IP。11.修改nginx配置文件location / proxy_pass http:/192.168.18.201; proxy_set_header X-Real-IP $remote_addr; #加上这一行指令说明:proxy_set_header语法:proxy_set_header header value 默认值: Host and Connection 使用字段:http, server, location 这个指令允许将发送到被代理服务器的请求头重新定
22、义或者增加一些字段。这个值可以是一个文本,变量或者它们的组合。proxy_set_header在指定的字段中没有定义时会从它的上级字段继承。12.重新加载一下配置文件rootnginx # service nginx reloadnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful重新载入 nginx:13.测试并查看日志略注,大家可以看到日志记录的还是代理的IP,没有显示真实客户端的IP
23、,为什么呢?我们来看一下httpd的配置文件。14. 查看并修改httpd配置文件rootweb1 # vim /etc/httpd/conf/httpd.conf注,大家可以这里记录日志的参数还是%h,下面我们修改一下参数。LogFormat %X-Real-IPi %l %u %t %r %s %b %Refereri %User-Agenti combinedLogFormat %h %l %u %t %r %s %b commonLogFormat %Refereri - %U refererLogFormat %User-agenti agent注,这是修改后的参数,将h%修改为%X
24、-Real-IPi,好的下面我们再来测试一下15.重启并测试测试日志略注,大家可以看到现在的日志里记录的IP地址就是真实的客户端地址了。好了,到这里Nginx代理后端一台服务器就演示到这里,下面我们继续说。五、Nginx之负载均衡注,大家可以看到,由于我们网站是发展初期,nginx只代理了后端一台服务器,但由于我们网站名气大涨访问的人越来越多一台服务器实在是顶不住,于是我们加了多台服务器,那么多台服务器又怎么配置代理呢,我们这里以两台服务器为案例,为大家做演示。1.upstream 负载均衡模块说明案例:下面设定负载均衡的服务器列表。upstream ip_hash;server 10.10.
25、21.13:80;server 10.10.21.14:80 down;server 10.10.21.15:8009 max_fails=3 fail_timeout=20s;server 10.10.21.16:8080;server location / proxy_pass ; 1.upstream是Nginx的HTTP Upstream模块,这个模块通过一个简单的调度算法来实现客户端IP到后端服务器的负载均衡。在上面的设定中,通过upstream指令指定了一个负载均衡器的名称。这个名称可以任意指定,在后面需要用到的地方直接调用即可。2.upstream 支持的负载均衡算法Nginx的
26、负载均衡模块目前支持4种调度算法,下面进行分别介绍,其中后两项属于第三方调度算法。 轮询(默认)。每个请求按时间顺序逐一分配到不同的后端服务器,如果后端某台服务器宕机,故障系统被自动剔除,使用户访问不受影响。Weight 指定轮询权值,Weight值越大,分配到的访问机率越高,主要用于后端每个服务器性能不均的情况下。ip_hash。每个请求按访问IP的hash结果分配,这样来自同一个IP的访客固定访问一个后端服务器,有效解决了动态网页存在的session共享问题。fai这是比上面两个更加智能的负载均衡算法。此种算法可以依据页面大小和加载时间长短智能地进行负载均衡,也就是根据后端服务器的响应时间
27、来分配请求,响应时间短的优先分配。Nginx本身是不支持fair的,如果需要使用这种调度算法,必须下载Nginx的upstream_fair模块。url_hash 此方法按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,可以进一步提高后端缓存服务器的效率。Nginx本身是不支持url_hash的,如果需要使用这种调度算法,必须安装Nginx 的hash软件包。3.upstream 支持的状态参数在HTTP Upstream模块中,可以通过server指令指定后端服务器的IP地址和端口,同时还可以设定每个后端服务器在负载均衡调度中的状态。常用的状态有: down,表示当前
28、的server暂时不参与负载均衡。backup,预留的备份机器。当其他所有的非backup机器出现故障或者忙的时候,才会请求backup机器,因此这台机器的压力最轻。max_fails,允许请求失败的次数,默认为1。当超过最大次数时,返回proxy_next_upstream 模块定义的错误。fail_timeout,在经历了max_fails次失败后,暂停服务的时间。max_fails可以和fail_timeout一起使用。注,当负载调度算法为ip_hash时,后端服务器在负载均衡调度中的状态不能是weight和backup。4.实验拓扑图5.配置nginx负载均衡rootnginx # v
29、im /etc/nginx/nginx.confupstream webservers server 10.10.21.223 weight=1; server 10.10.21.15 weight=1; server listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / proxy_pass http:/webservers; proxy_set_header X-Real-IP $remote_addr; 注,upstream是定义在server之外的,不能定义在server内部。定义好upstream之后,用proxy_pass引用一下即可。6.重新加载一下配置文件root