剖析Nginx 高級用法

Nginx除了衆所周之的可以搭建很好的LNMP平臺外,它還提供了許多其他高級功能,如反向代理,url重寫等。現在就剖析Nginx的深層功能。

安裝nginx

  1. # yum -y install pcre-devel  //nginx要用到的包 
  2. # groupadd -r nginx 
  3. # useradd -r -g nginx -s /sbin/nologin 
  4. #tar xf nginx-1.0.14.tar.gz 
  5. # ./configure \ 
  6.   --prefix=/usr \ 
  7.   --sbin-path=/usr/sbin/nginx \ 
  8.   --conf-path=/etc/nginx/nginx.conf \ 
  9.   --error-log-path=/var/log/nginx/error.log \ 
  10.   --http-log-path=/var/log/nginx/access.log \ 
  11.   --pid-path=/var/run/nginx/nginx.pid  \ 
  12.   --lock-path=/var/lock/nginx.lock \ 
  13.   --user=nginx \ 
  14.   --group=nginx \ 
  15.   --with-http_ssl_module \ 
  16.   --with-http_flv_module \ 
  17.   --with-http_stub_status_module \ 
  18.   --with-http_gzip_static_module \ 
  19.   --http-client-body-temp-path=/var/tmp/nginx/client/  
  20.   --http-proxy-temp-path=/var/tmp/nginx/proxy/ \ 
  21.   --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \ 
  22.   --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \ 
  23.   --http-scgi-temp-path=/var/tmp/nginx/scgi \ 
  24.   --with-pcre 
  25. # make && make  install

爲nginx提供服務腳本

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

一、Nginx---反向代理服務

 

所用有關服務器:

Nginx服務器:192.168.0.100

Web服務器:  192.168.0.11

 

在配置nginx反向代理服務之前,先說說什麼是反向代理。反向代理其實就是以代理服務器來接受Internet連接請求,然後,再把請求轉發給真正的服務器來響應。

  1. 編輯nginx服務器的配置文件 
  2.  location / { 
  3.   proxy_pass        http://192.168.0.11 //代理服務器的地址 
  4.   } 

在Web服務器上

  1. 首先安裝httpd提供Web服務  
  2. #service httpd start  
  3. #echo "<h1>192.168.0.11</h1>> /var/www/html/index.html  

此時訪問http://192.168.0.100,查看結果。

請求成功的轉發到了web服務器上。反向代理服務器工作正常。

二、爲反向代理啓用緩存功能

反向代理雖然保證了web服務器資源的安全性,但轉發過程卻降低了請求的響應速度。因此開啓緩存功能尤爲重要。下面通過兩組數據對比來展現緩存的優越性。以上述例子爲例。

在其他服務器上對http://192.168.0.100/index.html做壓力測試。

#ab -n 10000 -c 500 http://192.168.0.100

在開啓緩存服務前

每秒可平均處理152.17個請求,每個請求的平均響應時間約爲3.3s。

配置nginx反向代理的緩存功能

  1. 編輯nginx服務的配置文件 
  2. http { 
  3.   proxy_cache_path /var/www/cache levels=1:2 keys_zone=mycache:20m   
  4.      max_size=2048m inactive=60m;  levels:緩存級別 keys_zone保存了元數據,
  5. 名字爲mycache,大小爲20M 緩存數據最大爲2G  
  6.   proxy_temp_path /var/www/cache/tmp; 
  7.   ... 
  8.     location / { 
  9.       proxy_pass http://192.168.0.100/; 
  10.       proxy_cache mycache; 
  11.       proxy_cache_valid 200 302 60m;
  12.       proxy_cache_valid 404 1m; 
  13.     } 
  14.   } 
  15. #service nginx restart

此時再次測試網頁訪問壓力

此時的每秒可平均處理612.27個請求,每個請求的平均響應時間爲0.8s。對比可知緩存大大減少了響應時間。

三、反向代理多臺服務器實現負載均衡

實驗所需,此時再添加一臺Web服務器。地址爲:192.168.0.66

  1. #echo "<h1>192.168.0.66</h1>> /var/www/html/index.html 

在nginx服務上

  1. 編輯配置文件 
  2. upstream cluster {  
  3.     server 192.168.0.11 weight=1;  
  4.         server 192.168.0.66 weight=2
  5.    } 
  6. //使用upstream聲明一組可以被proxy_pass引用的服務器,weight指定權重,
  7. cluser是定義的名字 
  8. server{ 
  9.      listen       80; 
  10.         server_name  localhost; 
  11.         location / { 
  12.         proxy_pass  http://cluster; 
  13.         } 
  14. }   
  15. #service nginx restart

訪問服務:

 

輪詢響應成功。

四、URL重寫

url重寫使用的格式爲:rewrite  regex  replacement  flag

rewrite是關鍵字,regex是需要重定向的內容,replacement是重定向後的格式,flag表示以什麼的方法重寫。

flag有四種格式:

last:匹配規則後再次對全部規則進行匹配

這種方法有時會產生死循環,如

 rewrite ^/images/(.*\.jpg)$ http://192.168.0.100/images/$1 last

break:匹配後不再匹配後面的規則

redirect:臨時重定向標識,http協議代碼爲302

permanent:永久重定向標識,http協議代碼爲301

 

rewrite還支持if指令,用法爲:

    if (condition) { ... }

條件可以是:

(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. 編輯nginx配置文件 
  2.  location / { 
  3.          root   html; 
  4.          index  index.html index.htm; 
  5.          if (!-f $request_filename) { 
  6.          rewrite ^(/.*)$  /error.html permanent; 
  7.      } 
  8. #echo "ERROR" > /usr/html/error.html  
  9. #service nginx restart 

此時在瀏覽中輸入一個不存在網頁,如:http://192.168.0.100/aa.html

此時服務器自動跳轉到了error.html頁面上。url重寫成功。

那麼我們如何將訪問forum站點的請求重定向到bbs站點上呢?

  1. 編輯配置文件 
  2.  location / { 
  3.          root   html; 
  4.          index  index.html index.htm; 
  5.          rewrite ^/forum/(.*)$  http://bbs/$1  last; 
  6. #cd /usr/html 
  7. #mkdir bbs 
  8. #cd bbs 
  9. #vim index.html 
  10. This is BBS page 
  11. #service nginx restart 

訪問http://192.168.0.100/forum/

訪問頁面爲bbs站點的內容,url重寫成功。

五、安裝配置第三方模塊,實現upstream中對後端http server的健康狀態檢測

要實現此功能需額外的功能模塊對nginx打補丁。

下載地址:https://github.com/cep21/healthcheck_nginx_upstreams,模塊名稱爲ngx_http_healthcheck_module

在此使用的模塊爲healthcheck_nginx_upstreams.zip。須注意的是此模塊適用於nginx的1.0版本,若nginx版本過高則需要其他的模塊。

  1. #unzip healthcheck_nginx_upstreams.zip 
  2. 解壓後的文件爲cep21-healthcheck_nginx_upstreams-16d6ae7 
  3. #mv cep21-healthcheck_nginx_upstreams-16d6ae7 health  
  4. # tar xf nginx-1.0.14.tar.gz 
  5. # cd nginx-1.0.14 
  6. # patch -p1 < /root/health/nginx.patch  //對nginx大補丁 
  7. #./configure \    //重新編譯nginx 
  8.   --prefix=/usr \ 
  9.   --sbin-path=/usr/sbin/nginx \ 
  10.   --conf-path=/etc/nginx/nginx.conf \ 
  11.   --error-log-path=/var/log/nginx/error.log \ 
  12.   --http-log-path=/var/log/nginx/access.log \ 
  13.   --pid-path=/var/run/nginx/nginx.pid  \ 
  14.   --lock-path=/var/lock/nginx.lock \ 
  15.   --user=nginx \ 
  16.   --group=nginx \ 
  17.   --with-http_ssl_module \ 
  18.   --with-http_flv_module \ 
  19.   --with-http_stub_status_module \ 
  20.   --with-http_gzip_static_module \ 
  21.   --http-client-body-temp-path=/var/tmp/nginx/client/ \ 
  22.   --http-proxy-temp-path=/var/tmp/nginx/proxy/ \ 
  23.   --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \ 
  24.   --with-pcre \ 
  25.   --add-module=/root/nginx/health  //添加選項 
  26. # make && make install 

編輯配置文件

  1. upstream cluster { 
  2.    server 192.168.0.11 weight=1; //集羣服務器 
  3.    server 192.168.0.66 weight=2
  4.     healthcheck_enabled; //啓用檢查功能 
  5.     healthcheck_delay 1000;//檢查節點的間隔 
  6.     healthcheck_timeout 1000;//超時時間 
  7.     healthcheck_failcount 3;//允許的檢查失敗的次數 
  8.     healthcheck_send "GET /.health.html HTTP/1.0"; //檢查頁面 
  9.     } 
  10.     server { 
  11.         listen       80; 
  12.         server_name  localhost; 
  13.         location / {       
  14.         proxy_pass  http://cluster; 
  15.         } 
  16.         location /status {   //顯示後端服務器狀態 
  17.           healthcheck_status; 
  18.         } 
  19.   }     
  20. #service nginx start 
  21.   
  22. 在192.168.0.11服務器上  
  23. #echo "OK" > /var/www/html/.health.html
  24. 在192.168.0.66 #echo "OK" > /var/www/html/.health.html            

訪問頁面http://192.168.0.100發現輪詢服務正常。打開http://192.168.0.100/status

狀態顯示兩服務器工作正常。

在192.168.0.11上執行service httpd stop停止Web服務。再次刷新頁面:

狀態發生改變。而且此時訪問http://192.168.0.100會發現頁面只能定義在66節點上。

此時從新啓動192.168.0.11的Web服務,一切又恢復正常。

至此,nginx的高級功能介紹完畢。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章