nginx反向代理-负载均衡-URL重写

拓扑图:

 

一、nginx代理服务器安装配置:

1)安装Nginx:

1、解决依赖关系

编译安装nginx需要事先需要安装开发包组"Development Tools"和 "Development Libraries"。同时,还需要专门安装pcre-devel包:
# yum -y install pcre-devel
2、安装
首先添加用户nginx,实现以之运行nginx服务进程:
 
  1. # groupadd -r nginx  
  2. # useradd -r -g nginx –s /bin/false -M nginx  
  3. # tar xf nginx-1.2.3.tar.gz  
  4. # cd nginx-1.2.3  
接着开始编译和安装:
 
  1. # ./configure \ 
  2.   --prefix=/usr \           //指定nginx安装目录 
  3.   --sbin-path=/usr/sbin/nginx \      //指定nginx可执行二进制文件存放目录 
  4.   --conf-path=/etc/nginx/nginx.conf \  //指定nginx配置文件所在目录 
  5.   --error-log-path=/var/log/nginx/error.log \  //指定nginx错误日志所在目录 
  6.   --http-log-path=/var/log/nginx/access.log \  //指定HTTP访问日志文件目录 
  7.   --pid-path=/var/run/nginx/nginx.pid  \       //指定nginx的PID文件所在目录 
  8.   --lock-path=/var/lock/nginx.lock \      //指定nginx的lock文件所在目录 
  9.   --user=nginx \             //为nginx工作进程指定非特权用户 
  10.   --group=nginx \            //为nginx工作进程指定非特权用户组 
  11.   --with-http_ssl_module \    //加载ngx_http_ssl_module模块,使其支持ssl功能 
  12.   --with-http_flv_module \   //加载ngx_http_flv_module模块 
  13.   --with-http_stub_status_module \   //加载ngx_http_stub_status_module模块 
  14.   --with-http_gzip_static_module \   //加载ngx_http_gzip_static_module模块  
  15.   --http-client-body-temp-path=/var/tmp/nginx/client/ \  //指定HTTP客户端请求主体临时存放目录  
  16.   --http-proxy-temp-path=/var/tmp/nginx/proxy/ \   //指定HTTP代理临时文件存放目录 
  17.   --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \   //指定HTTP的Fastcgi临时文件存放目录 
  18.   --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \   //指定HTTP的Uwsgi临时文件存放目录 
  19.   --http-scgi-temp-path=/var/tmp/nginx/scgi \    //指定HTTP的Scgi临时文件存放目录 
  20.   --with-pcre    //强制支持pcre库 
  21. # make && make install 

2)为nginx提供SysV init脚本:

  1. 新建文件/etc/rc.d/init.d/nginx,内容如下:  
  2. #!/bin/sh  
  3. #  
  4. # nginx - this script starts and stops the nginx daemon  
  5. #  
  6. # chkconfig:   - 85 15   
  7. # description:  Nginx is an HTTP(S) server, HTTP(S) reverse \  
  8. #               proxy and IMAP/POP3 proxy server  
  9. # processname: nginx  
  10. # config:      /etc/nginx/nginx.conf  
  11. # config:      /etc/sysconfig/nginx  
  12. # pidfile:     /var/run/nginx.pid  
  13.    
  14. # Source function library.  
  15. . /etc/rc.d/init.d/functions  
  16.    
  17. # Source networking configuration.  
  18. . /etc/sysconfig/network  
  19.    
  20. # Check that networking is up.  
  21. [ "$NETWORKING" = "no" ] && exit 0  
  22.    
  23. nginx="/usr/sbin/nginx"  
  24. prog=$(basename $nginx)  
  25.    
  26. NGINX_CONF_FILE="/etc/nginx/nginx.conf"  
  27.    
  28. [ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx  
  29.    
  30. lockfile=/var/lock/subsys/nginx  
  31.    
  32. make_dirs() {  
  33.    # make required directories  
  34.    user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`  
  35.    options=`$nginx -V 2>&1 | grep 'configure arguments:'`  
  36.    for opt in $options; do  
  37.        if [ `echo $opt | grep '.*-temp-path'` ]; then  
  38.            value=`echo $opt | cut -d "=" -f 2`  
  39.            if [ ! -d "$value" ]; then  
  40.                # echo "creating" $value  
  41.                mkdir -p $value && chown -R $user $value  
  42.            fi  
  43.        fi  
  44.    done  
  45. }  
  46.    
  47. start() {  
  48.     [ -x $nginx ] || exit 5  
  49.     [ -f $NGINX_CONF_FILE ] || exit 6  
  50.     make_dirs  
  51.     echo -n $"Starting $prog: "  
  52.     daemon $nginx -c $NGINX_CONF_FILE  
  53.     retval=$?  
  54.     echo  
  55.     [ $retval -eq 0 ] && touch $lockfile  
  56.     return $retval  
  57. }  
  58.    
  59. stop() {  
  60.     echo -n $"Stopping $prog: "  
  61.     killproc $prog -QUIT  
  62.     retval=$?  
  63.     echo  
  64.     [ $retval -eq 0 ] && rm -f $lockfile  
  65.     return $retval  
  66. }  
  67.    
  68. restart() {  
  69.     configtest || return $?  
  70.     stop  
  71.     sleep 1  
  72.     start  
  73. }  
  74.    
  75. reload() {  
  76.     configtest || return $?  
  77.     echo -n $"Reloading $prog: "  
  78.     killproc $nginx -HUP  
  79.     RETVAL=$?  
  80.     echo  
  81. }  
  82.    
  83. force_reload() {  
  84.     restart  
  85. }  
  86.    
  87. configtest() {  
  88.   $nginx -t -c $NGINX_CONF_FILE  
  89. }  
  90.    
  91. rh_status() {  
  92.     status $prog  
  93. }  
  94.    
  95. rh_status_q() {  
  96.     rh_status >/dev/null 2>&1  
  97. }  
  98.    
  99. case "$1" in  
  100.     start)  
  101.         rh_status_q && exit 0  
  102.         $1  
  103.         ;;  
  104.     stop)  
  105.         rh_status_q || exit 0  
  106.         $1  
  107.         ;;  
  108.     restart|configtest)  
  109.         $1  
  110.         ;;  
  111.     reload)  
  112.         rh_status_q || exit 7  
  113.         $1  
  114.         ;;  
  115.     force-reload)  
  116.         force_reload  
  117.         ;;  
  118.     status)  
  119.         rh_status  
  120.         ;;  
  121.     condrestart|try-restart)  
  122.         rh_status_q || exit 0  
  123.             ;;  
  124.     *)  
  125.         echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"  
  126.         exit 2  
  127. esac  
而后为此脚本赋予执行权限:
 
  1. # chmod +x /etc/rc.d/init.d/nginx  
添加至服务管理列表,并让其开机自动启动:
 
  1. # chkconfig --add nginx  
  2. # chkconfig nginx on  
而后就可以启动服务并测试了:
 
  1. # service nginx start  

二、apache服务器配置

  1. 1)安装apache: 
  2. # yum -y install httpd 
  3. 2)安装php 
  4. # yum -y install php 
  5. 添加php测试页面 
  6. # vim /var/www/html/index.php 
  7. 内容如下: 
  8. <?php 
  9. phpinfo() 
  10. ?> 
  11. 重启httpd服务并访问试试 
  12. # service httpd restart 

三、配置172.16.11.11的nginx代理172.16.11.21的apache的http的服务

Nginx实现代理需要proxy模块,默认nginx已经具备这一功能,无需进行编译该模块,我们要做的就是配置nginx的主配置文件即可;
编辑nginx的主配置文件,找到nginx的默认server的location选项
注释以下两行:
 
  1. #root   html;  
  2. #index  index.html index.htm;  

 添加如下行,制定代理的web服务器地址

  1. proxy_pass http://172.16.11.21; 
检查nginx配置文件并重启nginx服务
 
  1. # service nginx configtest 
  2. # service nginx restart 
验证nginx代理后端web服务的效果

通过以上配置nginx成功实现了反向代理后端web服务的作用,但是这种方法并不能在nginx代理服务器上实现缓存的功能,所以接下来我们就来说说怎样在nginx上实现缓存;
在对nginx实现缓存之前,我们先对nginx的代理进行压力测试,以便显现出缓存的效果;
在其他另外的主机上执行如下命令通过nginx代理进行压力测试:
 
  1. # ab -n 10000 -c 100 http://172.16.11.11/index.php 
  2. Document Path:          /index.php 
  3. Document Length:        38239 bytes 
  4. Concurrency Level:      100 
  5. Time taken for tests:   154.738780 seconds 
  6. Complete requests:      10000 
  7. Failed requests:        0 
  8. Write errors:           0 
  9. Total transferred:      384000000 bytes 
  10. HTML transferred:       382390000 bytes 
  11. Requests per second:    64.63 [#/sec] (mean)    //每秒钟响应64个请求// 
  12. Time per request:       1547.388 [ms] (mean)    //每个请求用时1547毫秒// 
  13. Time per request:       15.474 [ms] (mean, across all concurrent requests) //并发请求100个用时15秒// 
  14. Transfer rate:          2423.44 [Kbytes/sec] received   //平均传输速率2423kb/s// 
  15. 在其他另外的主机上执行如下命令通过直接访问web页面进行压力测试: 
  16. # ab -n 10000 -c 100 http://172.16.11.21/index.php 
  17. Document Path:          /index.php 
  18. Document Length:        38025 bytes 
  19. Concurrency Level:      100 
  20. Time taken for tests:   69.886173 seconds 
  21. Complete requests:      10000 
  22. Failed requests:        0 
  23. Write errors:           0 
  24. Total transferred:      382159368 bytes 
  25. HTML transferred:       380437992 bytes 
  26. Requests per second:    143.09 [#/sec] (mean)    //每秒钟响应143个请求// 
  27. Time per request:       698.862 [ms] (mean)      //每个请求用时698毫秒// 
  28. Time per request:       6.989 [ms] (mean, across all concurrent requests) //并发请求100个用时6秒// 
  29. Transfer rate:          5340.14 [Kbytes/sec] received   //平均传输速率5340kb/s// 

通过以上压力测试对比发现,尽管采用nginx实现反向代理但nginx没有缓存功能,页面响应速度不升反而会大大降低;

为nginx反代服务器提供缓存;

  1. 编辑nginx的主配置文件,找到http选项,添加如下内容: 
  2. proxy_cache_path /var/www/cache levels=1:2 keys_zone=mycache:20m; //定义缓存路径,缓存级别和内存键区域名称及空间大小// 
  3. max_size=2048m inactive=60m;  //最大缓存空间大小和非活动时长(超过该时长缓存过期)// 
  4. proxy_temp_path /var/www/cache/tmp;  //代理临时目录,需要事先创建// 
  5. 找到Location选项,添加如下内容: 
  6. proxy_pass http://172.16.11.21;  //制定反代服务器// 
  7. proxy_cache mycache;  //定义缓存名称,要与上述内存键区域名称保持一致// 
  8. proxy_cache_valid 200 302 60m;  //定义请求页面响应码为200和302的页面缓存时长为60分钟// 
  9. proxy_cache_valid 404 1m;   //定义请求页面响应码为404的页面缓存时长为1分钟// 
  10. 创建缓存目录 
  11. # mkdir /var/www/cache/tmp -pv 
  12. 检查nginx配置文件语法并重启nginx服务 
  13. # service nginx configtest 
  14. # service nginx restart 
  15. 首先在其他另外的主机上执行几次如下命令通过nginx代理进行压力测试使缓存中充满访问数据; 
  16. # ab -n 1000 -c 20 http://172.16.11.11/index.php 
  17. 然后利用上述同样的测试方法通过nginx代理进行压力测试 
  18. # ab -n 10000 -c 100 http://172.16.11.11/index.php 
  19. Document Path:          /index.php 
  20. Document Length:        38239 bytes 
  21. Concurrency Level:      100 
  22. Time taken for tests:   79.248259 seconds 
  23. Complete requests:      10000 
  24. Failed requests:        0 
  25. Write errors:           0 
  26. Total transferred:      384478146 bytes 
  27. HTML transferred:       382865409 bytes 
  28. Requests per second:    126.19 [#/sec] (mean)   //每秒钟响应126个请求// 
  29. Time per request:       792.483 [ms] (mean)     //每个请求用时792毫秒// 
  30. Time per request:       7.925 [ms] (mean, across all concurrent requests) //并发请求100个用时7秒// 
  31. Transfer rate:          4737.85 [Kbytes/sec] received  //平均传输速率4737kb/s// 

通过上述对nginx反向代理进行压力测试前后对比发现,自从引入了nginx的缓存功能大大提升了页面响应速度,同时也很好的提升的用户的感知度;
以上就是nginx反向代理引入缓存功能的介绍;

四、配置nginx代理服务器使用户访问的页面部分代理到后台服务器响应

配置nginx主配置文件,在server选项下定义两个location
 
  1. location / {                     //定义访问路径为”/”时直接在nginx服务器响应// 
  2.             root   html; 
  3.             index  index.html index.htm; 
  4. location /images/ {      //定义访问路径为”/images/”时代理到Apache服务器响应// 
  5.              proxy_pass http://172.16.11.21/images/; 
  6.              proxy_cache mycache; 
  7.              proxy_cache_valid 200 302 60m; 
  8.              proxy_cache_valid 404 1m; 
配置apache服务器在主目录下面新建images目录并新建页面
 
  1. # mkdir /var/www/html/images 
  2. # vim /var/www/html/images/index.html 
  3. 添加如下内容: 
  4. <h1>apache</h1> 
  5. 重启nginx和后端apache服务器 
  6. # service nginx restart 
  7. # service httpd restart 
此时访问一下试试

通过以上访问结果成功的实现了部分代理后端服务响应用户请求。

五、配置nginx代理服务器实现负载均衡,需要用到nginx的upstream模块

1)配置nginx主配置文件,在http选项下添加如下内容
 
  1. upstream cluster {                   //定义后端负载均衡服务器名称// 
  2.         server 172.16.11.21 weight=1;  //指定后端服务器和权重// 
  3.         server 172.16.11.22 weight=2
  4. 在server选项下添加如下内容 
  5. location / { 
  6.              proxy_pass http://cluster;   //反代指向定义的负载均衡服务器// 
2)这里新增一台apache服务器,安装方法见步骤一,这里添加测试页面index.html,内容为<h1>RS2</h1> 
3)这里将nginx的缓存功能去掉,为了演示效果;
验证以下nginx的负载均衡的效果吧

结果证明nginx反向代理服务器方便快捷的实现的负载均衡的功能;

解析:

upstream
   语法:upstream name { ... } //声明一组可以被proxy_pass和fastcgi_pass引用的服务器;这
         些服务器可以使用不同的端口,并且也可以使用Unix Socket;也可以为服务器指定不同
         的权重//
server
   语法:server name [parameters] //其中的name可以是FQDN,主机地址,端口或unix套接字;
   如果FQDN解析的结果为多个地址,则每个地址都会被用到;[parameters]有以下选项:
weight = NUMBER - 设定权重,默认为1.
max_fails = NUMBER - 在fail_timeout指令设定的时间内发往此server的不成功的请求次数,达到
   此数目后,此服务器将变为不可操作状态;默认值为1;设定为0值则禁用此功能;
fail_timeout = TIME - 默认为10秒;
down - marks server as permanently offline, to be used with the directive ip_hash.
backup - (0.6.7 or later) only uses this server if the non-backup servers are all down
   or busy (cannot be used with the directive ip_hash)//

六、配置nginx实现URL重写

首先讲解以下URL重写的相关知识:

URL重写用到的指令是rewrite

rewrite指令的用法:
rewrite regex replacement flag 即将regex替换为replacemen+flag标志位的格式;
比如:rewrite /images/(.*\.jpg) http://172.16.0.1/images/$1 即web浏览器中出现/images/(.*\.jpg)的访问路径格式将被替换为http://172.16.0.1/images/$1路径访问;
上述/images/(.*\.jpg)路径还可以写成^/images/(.*\.jpg)或者^/images/(.*\.jpg)$等,这里意思很明显,相信你懂的;
注意:/images/(.*\.jpg)路径指的是浏览器中除了IP地址以外的路径;
flag标志位讲解:
在apache模块中标志位很多,而nginx的标志位仅有4种:
last - completes processing of current rewrite directives and restarts the process (including rewriting) with a search for a match on the URI from all available locations.(表示匹配到的访问路径进行持续性检查,但是容易造成死循环);
break - completes processing of current rewrite directives and non-rewrite processing continues within the current location block only.( 表示匹配到的访问路径只进行一次性检查,有效的解决了死循环的问题);
redirect - returns temporary redirect with code 302; it is used if the substituting line begins with http://(表示临时重定向,返回代码302);
permanent - returns permanent redirect with code 301(表示永久重定向,返回代码301);
例如:设置一个简单的URL重写:
某网站原有的论坛访问路径为/forum/,但后来根据要求需要更改为/bbs,于是,就可以通过下面的方法实现:rewrite ^/forum/?$ /bbs/ permanent;
其中/bbs/是实实在在存在的路径;
在进行URL重写的时候经常会用到if判断语句,当满足一定条件时进行URL重写;
1、if指令:
语法: if (condition) { ... }
应用环境: server, location
条件表达式:
1、变量名; false values are: empty string ("", or any string starting with "0";)
2、对于变量进行的比较表达式,可使用=或!=进行测试;
3、正则表达式的模式匹配:
~ 区分字母大小写的模式匹配
~* 不区分字母大小写的模式匹配
!~ 和 !~* 分别对上面的两种测试取反
4、测试文件是否存在-f或!-f
5、测试目录是否存在-d或!-d
6、测试目录、文件或链接文件的存在性-e或!-e
7、检查一个文件的执行权限-x或!-x
在正则表达式中,可以使用圆括号标记匹配到的字符串,并可以分别使用$1,$2,...,$9进行引用;
例如:
1)判断用户的浏览器类型(常用到手机和PC机浏览器):
  if ($http_user_agent ~* MSIE) {
     rewrite ^(.*)$ /msie/$1 break;
  }
  if ($http_user_agent ~* opera) {
     rewrite ^(.*)$ /opera/$1 break;
  }
2)如果用户请求的页面不存在,实现自定义跳转:
  if (!-f $request_filename) {
     rewrite ^(/.*)$ /rewrite.html permanent;
  }
例如:编辑nginx的主配置文件,在server中的location中添加如下内容:
  location / {
    root html;
    index index.html index.htm;
    if (!-f $request_filename) {
    rewrite /.* /error.html permanent;
    }
  }
在/usr/html中创建error.html页面:内容为ERROR
重启nginx服务并访问:

3)实现域名跳转
 
  1. server 
  2. listen 80; 
  3. server_name jump.magedu.com; 
  4. index index.html index.php; 
  5. root /www/htdocs; 
  6. rewrite ^/ http://www.magedu.com/; 
  7. }       //如果用户访问的是jump.magedu.com则跳转到http://www.magedu.com/ 
  8. 例如:在nginx主配置文件server中添加如下内容: 
  9. server 
  10. listen 80; 
  11. server_name test.magedu.com; 
  12. index index.html index.php; 
  13. rewrite ^/ http://tomcat.magedu.com/; 
  14. 在本地主机hosts文件中添加如下内容: 
  15. 172.16.11.11 test.magedu.com 
  16. 172.16.11.21 tomcat.magedu.com 
重启nginx服务并访问:

4)实现域名镜像
  1. server 
  2. listen 80; 
  3. server_name mirror.magedu.com; 
  4. index index.html index.php; 
  5. root /www/htdocs; 
  6. rewrite ^/(.*)$ http://www.magedu.com/$1 last; 
5)简单的防盗链配置:
  1. location ~* \.(gif|jpg|png|swf|flv)$ { 
  2.   valid_referers none blocked www.magedu.com; 
  3.   if ($invalid_referer) { 
  4.     rewrite ^/ http://www.magedu.com/403.html; 
  5.     # return 404 
  6.   } 
  7. }   
解析:
   第一行:gif|jpg|png|swf|flv,表示对gif、jpg、png、swf、flv后缀的文件实行防盗链
   第二行:www.magedu.com,表示对www.magedu.com这个来路进行判断if{}里面内容的意思,如果
           来路不是指定来路就跳转到错误页面,当然直接返回404也是可以的。

更多延伸内容如下:

  1. if (! -e $request_filename) { 
  2.       rewrite ^/user/([0-9]+)/?$ /view.php?go=user_$1 last; 
  3.       rewrite ^/component/id/([0-9]+)/?$ /page.php?pageid=$1 last; 
  4.       rewrite ^/component/([^/]+)/?$ /page.php?pagealias=$1 last; 
  5.       rewrite ^/category\_([0-9]+)\.htm$ http://$host/category/$1/ permanent; 
  6.       rewrite ^/showday\_([0-9]+)\_([0-9]+)\_([0-9]+)\.htm$ http://$host/date/$1/$2/$3/ permanent; 
  7.       showday_1_2_3.htm $host/date/1/2/3/ 

常用的变量:

  1. $arg_PARAMETER        This variable contains the value of the GET request variable PARAMETER if present in the query string. 
  2. $args                 This variable contains the query string in the URL, for example foo=123&bar=blahblah if the URL is http://example1. com/? foo=123&bar=blahblah 
  3. $binary_remote_addr   The address of the client in binary form. 
  4. $body_bytes_sent      The bytes of the body sent. 
  5. $content_length       This variable is equal to line Content-Length in the header of request. 
  6. $content_type         This variable is equal to line Content-Type in the header of request. 
  7.  
  8. $document_root        This variable is equal to the value of directive root for the current request. 
  9. $document_uri         The same as $uri. 
  10. $host                 This variable contains the value of the 'Host' value in the request header, or the name of the server processing if the 'Host' value is not available. 
  11. $http_HEADER          The value of the HTTP header HEADER when converted to lowercase and with "dashes" converted to "underscores", for example, $http_user_agent, $http_referer. 
  12. $is_args              Evaluates to "?" if $args is set, returns "" otherwise. 
  13. $request_uri          This variable is equal to the *original* request URI as received from the client including the args. It cannot be modified. Look at $uri for the post-rewrite/altered URI. Does not include host name. Example: "/foo/bar.php?arg=baz". 
  14. $scheme               The HTTP scheme (that is http, https). Evaluated only on demand, for example: rewrite ^(.+)$ $scheme://example.com$1 redirect; 
  15. $server_addr          This variable contains the server address. It is advisable to indicate addresses correctly in the listen directive and use the bind parameter so that a system call is not made every time this variable is accessed. 
  16. $server_name          The name of the server. 
  17. $server_port          This variable is equal to the port of the server, to which the request arrived. 
  18. $server_protocol      This variable is equal to the protocol of request, usually this is HTTP/1.0 or HTTP/1.1. 
  19. $uri                  This variable is equal to current URI in the request (without arguments, those are in $args.) It can differ from $request_uri which is what is sent by the browser. Examples of how it can be modified are internal redirects, or with the use of index. Does not include host name. Example: "/foo/bar.html" 

七、安装配置nginx第三方模块,实现upstream中对后端http server的健康状态检测:

模块下载地址:https://github.com/cep21/healthcheck_nginx_upstreams;模块名称:ngx_http_healthcheck_module
安装配置方法:
1、首先解压healcheck模块到某路径下,这里假设为/health/healthcheck_nginx_upstreams
  1. # mkdir /health/ 
  2. # unzip healthcheck_nginx_upstreams.zip -d /health/ 
  3. # mv /health/cep21-healthcheck_nginx_upstreams-16d6ae7 /health/healthcheck_nginx_upstreams 
2、对nginx打补丁
  1. 首先解压nginx,并进入nginx源码目录: 
  2. # tar xf nginx-1.0.14.tar.gz //注:需要nginx版本匹配,不支持nginx-1.2.2及以上版本
  3. # cd nginx-1.0.14 
  4. # patch -p1 < /health/healthcheck_nginx_upstreams/nginx.patch 
  5. 而后编译nginx,在执行configure时添加类似下面的选项: 
  6. --add-module=/health/healthcheck_nginx_upstreams 
  7. 所以,这里就使用如下命令: 
  8. # ./configure \ 
  9.   --prefix=/usr \ 
  10.   --sbin-path=/usr/sbin/nginx \ 
  11.   --conf-path=/etc/nginx/nginx.conf \ 
  12.   --error-log-path=/var/log/nginx/error.log \ 
  13.   --http-log-path=/var/log/nginx/access.log \ 
  14.   --pid-path=/var/run/nginx/nginx.pid  \ 
  15.   --lock-path=/var/lock/nginx.lock \ 
  16.   --user=nginx \ 
  17.   --group=nginx \ 
  18.   --with-http_ssl_module \ 
  19.   --with-http_flv_module \ 
  20.   --with-http_stub_status_module \ 
  21.   --with-http_gzip_static_module \ 
  22.   --http-client-body-temp-path=/var/tmp/nginx/client/ \ 
  23.   --http-proxy-temp-path=/var/tmp/nginx/proxy/ \ 
  24.   --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \ 
  25.   --with-pcre \ 
  26.   --add-module=/health/healthcheck_nginx_upstreams 
  27. # make && make install 
  28. 编辑nginx的主配置文件: 
  29. http选项中添加: 
  30. upstream cluster { 
  31.         server 172.16.11.21 weight=1
  32.         server 172.16.11.22 weight=2
  33.      healthcheck_enabled; 
  34.         healthcheck_delay 1000; 
  35.         healthcheck_timeout 1000; 
  36.         healthcheck_failcount 2; 
  37.         healthcheck_expected 'OK'; 
  38.         healthcheck_send "GET /.health HTTP/1.0"; 
  39. Server中添加location选项内容: 
  40. location / {  
  41.             proxy_pass http://cluster; 
  42. location /stat { 
  43.       healthcheck_status; 
  44.   } 
重启nginx和后端apache服务并访问:

关闭172.16.11.21apache服务

以上结果表明nginx反向代理成功实现了对后端代理服务器的健康状况检查;

ngx_http_healthcheck_module模块的使用方法:

1、此模块支持的指令有:

healthcheck_enabled 启用此模块
healthcheck_delay对同一台后端服务器两次检测之间的时间间隔,单位毫秒,默认为1000;
healthcheck_timeout进行一次健康检测的超时时间,单位为毫秒,默认值2000;
healthcheck_failcount对一台后端服务器检测成功或失败多少次之后方才确定其为成功或失败,并实现启用或禁用此服务器;
healthcheck_send为了检测后端服务器的健康状态所发送的检测请求;如:healthcheck_send "GET /health HTTP/1.0" 'Host: www.magedu.com';//注意仅支持HTTP1.0版本协议//
healthcheck_expected期望从后端服务器收到的响应内容;如果未设置,则表示从后端服务器收到200状态码即为正确;
healthcheck_buffer健康状态检查所使用的buffer空间大小;
healthcheck_status通过类似stub_status的方式输出检测信息,使用方法如下:
location /stat {
healthcheck_status;
}

 

 

本文出自 “彼岸” 博客,请务必保留此出处http://wjw7702.blog.51cto.com/5210820/1095989

posted @ 2013-04-23 23:12  ~吉尔伽美什  阅读(638)  评论(0编辑  收藏  举报