一、实验前准备
1.所需主机
rs2:172.16.133.22
node1:172.16.133.11
rs1:172.16.133.1
2.软件安装
rs2:nginx安装
参照:http://5142926.blog.51cto.com/5132926/931149


node1:http,php安装
yum -y install httpd
yum -y install php


二、nginx实例扩展
1.nginx反代
rs2:
修改nginx主配置文件
 

 
  
  1. vim /etc/nginx/nginx.conf  
  2.     server {  
  3.     listen 80;  
  4.     server_name qinqin.magedu.com;  
  5.     location / {  
  6.       proxy_pass http://myproject;  
  7.     }  
  8.     }  

然后再在网页中打开http://172.16.133.22


2.nginx缓存
rs2:
先对http://172.16.133.22进行压力测试
 

 
  
  1. ab -c 500 -n 10000 http://172.16.133.22/index.php  

然后添加缓存控制(这里我们用nginx自带的,一般情况用memcache),这里cache是存在本地磁盘上的
 

 
  
  1. vim /etc/nginx/nginx.conf  
  2. http {  
  3.     include       mime.types;  
  4.     default_type  application/octet-stream;  
  5.     proxy_cache_path /var/www/cache levels=1:2 keys_zone=mycache:20m  
  6.     max_size=2048m inactive=60m;  
  7.     proxy_temp_path /var/www/cache/tmp;  
  8.     sendfile        on;  
  9.     keepalive_timeout  65;  
  10.     server {  
  11.         listen       80;  
  12.         server_name  localhost;  
  13.         location / {  
  14.           proxy_pass http://172.16.133.11;  
  15.           proxy_cache mycache;  
  16.           proxy_cache_valid 200 302 60m;  
  17.           proxy_cache_valid 404 1m;  
  18.         }  
  19.         error_page   500 502 503 504  /50x.html;  
  20.         location = /50x.html {  
  21.             root   html;  
  22.         }  

重启nginx服务
重新对http://172.16.133.22进行压力测试

 
  
  1. ab -c 500 -n 10000 http://172.16.133.22/index.php  


 

效果很明显
3.负载均衡
node1:
 

 
  
  1. cd /var/www/html  
  2. rm index.php  
  3. vim index.html  
  4.     <h1>world</h1>  

编辑nginx主配置文件
 

 
  
  1. vim /etc/nginx/nginx.conf  
  2.     http {  
  3.     include       mime.types;  
  4.     default_type  application/octet-stream;  
  5.     proxy_cache_path /var/www/cache levels=1:2 keys_zone=mycache:20m  
  6.     max_size=2048m inactive=60m;  
  7.     proxy_temp_path /var/www/cache/tmp;  
  8.     sendfile        on;  
  9.     keepalive_timeout  65;  
  10.  upstream cluster {  
  11.            server 172.16.133.11 weight=1;  
  12.            server 172.16.133.1  weight=1;  
  13.         }  
  14.     server {  
  15.         listen       80;  
  16.         server_name  localhost;  
  17.         location / {  
  18.           proxy_pass http://cluster;  
  19.           proxy_cache mycache;  
  20.           proxy_cache_valid 200 302 60m;  
  21.           proxy_cache_valid 404 1m;  
  22.         }  
  23.         error_page   500 502 503 504  /50x.html;  
  24.         location = /50x.html {  
  25.             root   html;  
  26.         }  
  27.     }  

然后访问http://172.16.133.22

 


4.rewrite用法
①.rewrite指令的语法:
s@\(patt\)ern@\1@
例如:
rewrite ^/p_w_picpaths/(.*\.jpg)$  /p_w_picpaths2/$1 break;
rewrite ^/abc/.*$ /$1/abc/ last

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://
临时重定向
permanent - returns permanent redirect with code 301
永久重定向
②.一个简单的url重写
node1:
 

 
  
  1. cd /var/www/html  
  2. mkdir /p_w_picpaths  
  3. cd p_w_picpaths/  
  4. vim index.html  
  5.     <h1>hello</h1>  
  6. rs2:  
  7. vim /etc/nginx/nginx.conf  
  8.     location / {  
  9.     rewrite ^/p_w_picpaths/(.*\.html) http://172.16.133.11/p_w_picpaths/$1 break;  
  10.  }  

③.其他应用
Ⅰ.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. if ($http_user_agent ~* MSIE) {  
  2.   rewrite  ^(.*)$  /msie/$1  break;  
  3. }  
  4. wap.magedu.com  
  5. if ($http_user_agent ~* opera) {  
  6.   rewrite  ^(.*)$  /opera/$1  break;  
  7. }  

如果用户请求的页面不存在,实现自定义跳转:
 

 
  
  1. if (!-f $request_filename) {  
  2.       rewrite ^(/.*)$ /rewrite.html permanent;  
  3. }  

Ⅱ.实现域名跳转
 

 
  
  1. server  
  2. {  
  3. listen 80;  
  4. server_name jump.magedu.com;  
  5. index index.html index.php;  
  6. root /www/htdocs;  
  7. rewrite ^/ http://www.magedu.com/;  
  8. }  

Ⅲ.实现域名镜像
 

 
  
  1. server  
  2. {  
  3. listen 80;  
  4. server_name mirror.magedu.com;  
  5. index index.html index.php;  
  6. root /www/htdocs;  
  7. rewrite ^/(.*)$ http://www.magedu.com/$1 last;  
  8. }  

Ⅳ.简单的防盗链配置:
 

 
  
  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/  
  8. }  
  9. server {  
  10.  listen 80 default;  
  11.  server_name *.mysite.com;  
  12.  rewrite ^ http://mysite.com$request_uri permanent;  
  13. }  

Ⅴ.设定错误日志格式及级别:
 

 
  
  1. http {  
  2. log_format combined '$remote_addr - $remote_user [$time_local] ' 
  3.     '"$request" $status $body_bytes_sent ' 
  4.     '"$http_referer" "$http_user_agent"';  
  5. access_log /var/log/nginx/access.log combined;  
  6. error_log /var/log/nginx/error.log crit;  
  7. ...  
  8. }  

Ⅵ.记录类似apache格式的日志:
 

 
  
  1. log_format main '$remote_addr - $remote_user [$time_local] ' 
  2.     '"$request" $status $body_bytes_sent "$http_referer" ' 
  3.     '"$http_user_agent" "$http_x_forwarded_for"';  
  4. access_log /var/log/nginx/access.log main;  

Ⅶ.启用日志缓存:
 

 
  
  1. http {  
  2.  ...  
  3.  open_log_file_cache max=1000 inactive=20s min_uses=2 valid=1m;  
  4.  ...  
  5. }  
  6. Max        Maximal number of descriptors in the cache, with overflow Least Recently Used removed (LRU)  
  7. Inactive   Sets the time after which descriptor without hits during this time are removed; default is 10 seconds  
  8. min_uses   Sets the minimum number of file usage within the time specified in parameter inactive, after which the file descriptor will be put in the cache; default is 1  
  9. Valid      Sets the time until it will be checked if file still exists under same namedefault is 60 seconds  
  10. Off        Disables the cache  

④.设定限速
Ⅰ.为某个特定路径限速:
 

 
  
  1. server {  
  2.    server_name www.magedu.com;  
  3.  
  4.   location /downloads/ {  
  5.     limit_rate 20k;  
  6.     root /web/downloads/;  
  7.   }  
  8.   ..  
  9. }  
  10.  

Ⅱ.限制搜索引擎的bot速度:
 

 
  
  1. if ($http_user_agent ~ Google|Yahoo|MSN|baidu) {  
  2.   limit_rate 20k;  
  3.  }  

常用的变量:
$arg_PARAMETER        This variable contains the value of the GET request variable PARAMETER if present in the query string.
$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
$binary_remote_addr   The address of the client in binary form.
$body_bytes_sent      The bytes of the body sent.
$content_length       This variable is equal to line Content-Length in the header of request.
$content_type         This variable is equal to line Content-Type in the header of request.
$document_root        This variable is equal to the value of directive root for the current request.
$document_uri         The same as $uri.
$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.
$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.
$is_args              Evaluates to "?" if $args is set, returns "" otherwise.
$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".
$scheme               The HTTP scheme (that is http, https). Evaluated only on demand, for example: rewrite ^(.+)$ $scheme://example.com$1 redirect;
$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.
$server_name          The name of the server.
$server_port          This variable is equal to the port of the server, to which the request arrived.
$server_protocol      This variable is equal to the protocol of request, usually this is HTTP/1.0 or HTTP/1.1.
$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"
三、安装配置第三方模块,实现upstream中对后端http server的健康状态检测:
模块下载地址:https://github.com/cep21/healthcheck_nginx_upstreams;模块名称:ngx_http_healthcheck_module
安装配置方法:
1、首先解压healcheck模块到某路径下,这里假设为/tmp/healthcheck_nginx_upstreams
2、对nginx打补丁
首先解压nginx,并进入nginx源码目录:
tar xf nginx-1.0.11.tar.gz
cd nginx-1.0.11
patch -p1 < /tmp/healthcheck_nginx_upstreams/nginx.patch
而后编译nginx,在执行configure时添加类似下面的选项:
--add-module=/tmp/healthcheck_nginx_upstreams
所以,这里就使用如下命令:
./configure \
  --prefix=/usr \
  --sbin-path=/usr/sbin/nginx \
  --conf-path=/etc/nginx/nginx.conf \
  --error-log-path=/var/log/nginx/error.log \
  --http-log-path=/var/log/nginx/access.log \
  --pid-path=/var/run/nginx/nginx.pid  \
  --lock-path=/var/lock/nginx.lock \
  --user=nginx \
  --group=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-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \
  --with-pcre \
  --add-module=/tmp/healthcheck_nginx_upstreams
make && make install
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';
healthcheck_expected
  期望从后端服务器收到的响应内容;如果未设置,则表示从后端服务器收到200状态码即为正确;
healthcheck_buffer
  健康状态检查所使用的buffer空间大小;
healthcheck_status
  通过类似stub_status的方式输出检测信息,使用方法如下:
  location /stat {
      healthcheck_status;
    }