Nginx從入門到掌握【(第3節(共3節)】

目錄:

  1. 關於Reserve Proxy;

  2. ngx_http_proxy_module模塊;

  3. ngx_http_upstream_module模塊;


正文:

一、關於Reserve Proxy.

wKioL1h-yg2gHQVnAABxEonhd4o006.png

Proxy請求過程分爲兩個階段:

  首先是請求報文從ClientProxy的過程,包含ClientProxy請求數據報文時的HTTP請求首部,nginx proxy接收到請求報文後,會將報文進行拆除,以瞭解報文內部請求的具體內容;並且去匹配本機的location;一旦匹配到,發現該報文請求內容是要發往後端服務器去請求的,此時proxy_server需要自己重新構建請求報文送往後端服務器


二、ngx_http_proxy_module模塊

作用: The ngx_http_proxy_module module allows passing requests to another  server.

格式:

location /uri{
     proxy_pass http://back_server:port/newuri; 
}

/uri --> /newuri  //上面示例中/uri對應的就是/newuri.

如果此處location後跟的/uri是通過模式匹配定義的,該種情形,實際請求的url路徑爲 http://back_server:port/newuri/uri   
如果location中使用了url重定向(rewrite)時,nignx將使用重定向之後的uri進行處理,而不是重定向之前的.

實驗一. 通過直接匹配與正則匹配的方式設置反向代理.

實驗環境:

    系統版本
     用途
    主機名
      IP
   CentOS7.3
  Nginx_Proxy
    nginx
   10.68.7.222
   CentOS6.8
  node_Server
    node1
   10.68.7.200
   CentOS6.8
  node_Server
    node2
   10.68.7.201
   Windows
     test
    Windows
   10.68.7.167

首先確認後端node服務器訪問正常:

[root@nginx conf]# curl 10.68.7.201
<h1> node1 </h1>
[root@nginx conf]# curl 10.68.7.202
<h1> node2 </h1>
[root@nginx conf]#

然後確保nginx_proxy代理服務器正常可用:

[root@nginx conf]# vim server1.conf 
  server {
        listen       8080;
        server_name  yangbin.com;

        charset utf-8;

        access_log  /data/nginx/logs/access.log;

        location / {
            root   /web/html/www;
            index  www.html index.html index.htm;
        }

        location /images/ {
            root /web/html/;
            index qq.jpg;
        }
  }

wKioL1h8elfQxUeDAAAzi3b1B98788.png

wKioL1h8ehuDq33aAAMIW4q7RK0099.png

然後開始配置proxy_pass:

[root@nginx conf]# vim server1.conf 
  server {
        listen       8080;
        server_name  yangbin.com;

        charset utf-8;

        access_log  /data/nginx/logs/access.log;
        
        location / {
            proxy_pass http://10.68.7.201/
            root   /web/html/www;
            index  www.html index.html index.htm;
        }   
        
        location /images/ {
            proxy_pass http://10.68.7.202/
            root /web/html/;
            index qq.jpg;
        }   
  }  
[root@nginx conf]# ../sbin/nginx -s reload

瀏覽器訪問測試:

wKiom1h8fnzCMTtZAAAqXGw0eh4249.png

wKioL1h8fnzCXxlLAAAumwub9uE859.png

從訪問的結果得出這樣的結論:訪問代理服務器ip,將是proxy_pass模塊進行響應!

此時查看node服務器的web訪問日誌,可以發現來源IP是nginx代理服務器的ip.

[root@node1 ~]# tail -1 /etc/httpd/logs/access_log 
10.68.7.222 - - [16/Jan/2017:23:55:04 +0800] "GET / HTTP/1.0" 200 17 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"
[root@node1 ~]#
[root@node2 ~]# tail -1 /etc/httpd/logs/access_log 
10.68.7.222 - - [17/Jan/2017:00:03:33 +0800] "GET / HTTP/1.0" 200 17 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"
[root@node2 ~]#

關於location匹配的其他情況:

第一種情況:

 location /images {
            proxy_pass http://10.68.7.202/images;
            root /web/html/;
            index qq.jpg;
 }

注:image/qq.jpg是node2服務器站點存放網頁的根目錄下的子目錄,該子目錄中包含qq.jpg圖片.

修改node2 httpd服務配置文件:

 [root@node2 html]# vim /etc/httpd/conf/httpd.conf 
  ...
  402 DirectoryIndex qq.jpg index.html index.html.var
  ...

瀏覽器訪問:

wKiom1h8hgqxiaD3AAJ_cb_E4nE121.png

查看node2服務器的access日誌文件:

[root@node2 html]# tail -1 /etc/httpd/logs/access_log 
10.68.7.222 - - [17/Jan/2017:00:29:43 +0800] "GET /images/ HTTP/1.0" 200 8863 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"
[root@node2 html]#

第二種情況:   

location  /frome/ {  
    proxy_pass http://10.68.7.202/bbs/;  
    ... 
}  //此時訪問yangbin.com:8080/frome時,返回的是/var/www/html/bbs/index.html中的內容,因爲/frome映射到了/bbs。

第三種情況:

location /js/ {
    proxy_pass 
    ... 
}  //此時訪問yangbin.com/js時,返回的是/var/www/html/js/index.html的內容.

查看node2服務器/js目錄下的網頁文件內容:

[root@node2 html]# vim js/index.html
 <h1> /var/www/html/js/index.html </h1>

瀏覽器訪問:

wKioL1h8izTzqAYAAAA5Ub3g2WY443.png

第四種情況:

location ~* \.(jpg|png|gif)$ {   // ~*表示不區分大小寫; 後面表示以.jpg, .png, .gif結尾的uri.
    proxy_pass http://10.68.7.202; 
}  //該種情況表示所有以.jpg, .png, .gif結尾的uri請求,都會代理至10.68.7.202.

如果採用的正則表達式匹配,則location部分會直接補到待訪問的IP地址後邊,如果ip地址後邊有其他路徑,也會將該路徑替換.

第五種情況:

location ~* \.(jpg|jpeg|png)$ {
    proxy_pass http://10.68.7.202;  
}    //此處如果是 http://10.68.7.202/, 即後面加個斜線是錯誤的,因爲對於模式匹配的proxy不允許有url路徑存在.

此情況下,在node1服務器下的/var/www/html/bbs/路徑下也應該有.jpg結尾的文件才行
瀏覽器訪問http://yangbin.com:8080/images/images.png,也會進行映射,實際的訪問路徑爲http://10.68.7.202/images/images.png.

瀏覽器驗證過程略.

注:關於以上各種情況帶來的訪問ip的問題:

  實驗一的情況,後端的node服務器上access_logs記錄的Client_ip是nginx反向代理服務的ip;而真實環境中,很多時候爲了分析用戶行爲,需要獲取訪問用戶的真實ip,因此以上情況的配置就有問題,因爲它將訪問用戶的ip統統轉化爲了代理服務器的ip.該問題的解決辦法,具體配置詳見"實驗2".


實驗2:向客戶端發送特定首部,記錄客戶端的ip.

官網文檔:
 http://nginx.org/en/docs/http/ngx_http_core_module.html#variables  
 http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header 

首先配置代理服務器:

location / {
            proxy_pass http://10.68.7.201/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;

            root   /web/html/www;
            index  www.html index.html index.htm;
        }

        location ~* \.(jpg|png|jpeg|gif)$  {
            proxy_pass http://10.68.7.202;
            proxy_set_header X-Real-IP $remote_addr;
            
            root /web/html/;
            index qq.jpg;
        }

然後修改node服務器配置文件的log格式:

[root@node1 ~]# vim /etc/httpd/conf/httpd.conf 
 ...
 497 #LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
 498 LogFormat "%{X-Real-IP}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined ////該行開頭"%h"改爲"%{X-Real-IP}i".
 499 LogFormat "%h %l %u %t \"%r\" %>s %b" common
 500 LogFormat "%{Referer}i -> %U" referer 
 501 LogFormat "%{User-agent}i" agent
 ...
[root@node1 ~]# service httpd restart
[root@node2 ~]# vim /etc/httpd/conf/httpd.conf 
 ...
 497 #LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
 498 LogFormat "%{X-Real-IP}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
 499 LogFormat "%h %l %u %t \"%r\" %>s %b" common
 500 LogFormat "%{Referer}i -> %U" referer
 501 LogFormat "%{User-agent}i" agent
 ...
[root@node2 ~]# service httpd restart

分別在瀏覽器訪問兩個location,然後到node服務器端查看訪問日誌:

[root@node1 ~]# tail -3 /etc/httpd/logs/access_log 
10.68.7.167 - - [17/Jan/2017:01:52:09 +0800] "GET / HTTP/1.0" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"
10.68.7.167 - - [17/Jan/2017:01:52:10 +0800] "GET / HTTP/1.0" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"
10.68.7.167 - - [17/Jan/2017:01:52:10 +0800] "GET / HTTP/1.0" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"
[root@node1 ~]#
[root@node2 ~]#  tail -3 /etc/httpd/logs/access_log 
10.68.7.167 - - [17/Jan/2017:01:52:08 +0800] "GET /images/images.png HTTP/1.0" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"
10.68.7.167 - - [17/Jan/2017:01:52:08 +0800] "GET /images/images.png HTTP/1.0" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"
10.68.7.167 - - [17/Jan/2017:01:52:08 +0800] "GET /images/images.png HTTP/1.0" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"
[root@node2 ~]#

10.68.7.167爲訪問客戶端的ip.


實驗3:nginx的代理緩存(proxy_cache)功能,加速用戶訪問站點的速度;

官網文檔:
http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache

此處可用壓測命令ab來測試緩存前後的效果.

ab命令的使用方法: http://024mj.blog.51cto.com/10252785/1684794

語法:

Syntax: proxy_cache_path PATH [levels=levels] [use_temp_path=on|off] 
e.g: proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=one:10m;

/data/nginx/cache: 表示緩存存儲的具體路徑;
levels=1:2 表示緩存的級別,1:2表示共有兩級緩存目錄,第一級緩存目錄共有1個字符表示,第二級緩存目錄共有2個字符表示,如果levels=1:2:3,表示共有3三級緩存目錄,第三級緩存目錄用三個字符表示;

keys_zone=one:10m表示在內存中找10兆大小的位置,取名爲one來存儲鍵值;
結果示例:

/data/nginx/cache/c/29/b7f54b2df7773722d382f4809d65029c
 目錄c:表示爲一級緩存目錄,共一個字符;

 目錄29:爲二級緩存目錄,共兩個字符;後面的一長串字符爲緩存的具體文件;


其他proxy_cache模塊配置語法說明:

Syntax: proxy_cache_methods GET | HEAD | POST ...;
Default: proxy_cache_methods GET HEAD;        
Context: http, server, location

作用:定義客戶端只有使用GET,HEAD或POST時纔會緩存;一般都是使用GET或HEAD時纔會緩存;
POST: 提交.
PUT:上傳.


Syntax: proxy_cache_min_uses number;
Default: proxy_cache_min_uses 1;
Context: http, server, location

作用:Sets the number of requests after which the response will be cached.
即設定用戶請求的內容被響應多少次之後纔會被緩存.
    

Syntax: proxy_cache_purge string ...;
Context: http, server, location
This directive appeared in version 1.5.7.

作用:purge表示修剪,淨化,清除; 即緩存管理;
使用場景:

1)緩存都有有效期限;在有效期限到來之前,緩存會一直有效;而在這期間,當後端服務器內容發生改變,用戶請求到仍然是舊的資源;
2)使用緩存修剪,網站管理人員可以限定自動將請求的緩存從本地緩存中刪除,這樣下次請求時將從後端服務器請求新的內容並緩存到本地,保證緩存與後端服務器資源的同步一致;
3)使用時注意權限問題,不能隨便授權;
             

Syntax:     proxy_cache_revalidate on | off;
Default: proxy_cache_revalidate off;
Context: http, server, location
This directive appeared in version 1.5.7.

作用:重新有效期驗證;即過期後重新校驗,就是當緩存過期後,它自動向後端服務器詢問資源是否有改動;如果沒有改動,就延長本地緩存過期時間繼續使用,可以避免佔據後端網絡帶寬;

        

Syntax: proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off ...;
Default: proxy_cache_use_stale off;
Context: http, server, location

作用:當用戶訪問某個資源,正好代理服務器緩存已過期,然後代理服務器向後端請求資源,正好後端服務器宕機了;此時代理服務器只能向客戶端返回請求的資源不存在;
而使用此選項,可以在這種情況下自定義給客戶端返回的錯誤信息,如timeout,updating,500,404等委婉信息;

Syntax: proxy_cache_valid [code ...] time;
Context: http, server, location

作用:Sets caching time for different response codes. For example, the following directives:

例:

  proxy_cache_valid 200 302 10m;
  proxy_cache_valid 404      1m;
按照響應碼來進行緩存;自定義緩存時長,而不用默認的;


三、ngx_http_upstream_module模塊;

語法:

Syntax: upstream name { ... }
Default: —
Context: http

配置:

[root@nginx conf]# vim nginx.conf   
 http {
     ...
     upstream user-defined { 
         server 10.68.7.201;
         server 10.68.7.202;
     }
     ...
     include server1.conf;
 }
[root@nginx conf]# vim server1.conf 
 ...
 location / {
            proxy_pass http://user-defined/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;

            root   /web/html/www;
            index  www.html index.html index.htm;
 }
 ...

瀏覽器訪問即會出現輪詢的情況;

wKioL1h8pGLBkj9jAAAutR3VSv8963.png

wKiom1h8pGODvhc8AAAw44a0xbQ605.png

注:
upstream和proxy_pass的區別:proxy_pass後面只能定義一個ip站點;upstream則可以把多個ip站點做成一個組(只能defined在http中),放在proxy_pass模塊後面以特定的方式來調用;
還要注意:
   The ngx_http_upstream_module module is used to define groups of servers that can be referenced by the proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, and memcached_pass directives.

upstream模塊默認是加權輪詢的,只不過權重都等於1.

其他upstream模塊選項:

Syntax: server address [parameters];
Default: —
Context: upstream

The following parameters can be defined:
 1) weight=number
 2) max_conns=number
 3) fail_timeout=time
 4) max_conns=number  
 5) max_fails=number  //用來做健康狀態檢查,嘗試多少次連接後還連接不上,就將其標記爲失效,並將其移除;
 6) fail_timeout=time  //定義超時時間;
 7) backup  //標記爲備用服務器,當另一臺服務器可用時,被標記的這臺服務器不會提供服務,只有當另一外服務器不可用時,被標記的這臺服務器纔會主動提供服務。一般把proxy服務器自己當做備用服務器;
 8)down  //標記爲永久下線,使用場景:後臺服務器需要升級且不支持平滑升級的情況下;
例如:    

upstream user-defined {
    server 10.68.7.200 weight=3;
    server 10.68.7.201;

//這樣定義完的效果是7.200站點的資源刷新三下後纔會輪詢到7.201上面;

Syntax: ip_hash;
Default: —
Context: upstream

作用:算法指令,指客戶端訪問到哪個站點後,刷新不會跳轉到其他站點,指session綁定,原地址綁定;
ip_hash可能有損負載均衡效果; 
e.g:

upstream user-defined {
     ip_hash;
     server 10.68.7.201;
     server 10.68.7.202;
}
upstream user-defined {
     server 10.68.7.201 max_fails=2 fail_timeout=2;
     server 10.68.7.202 max_fails=2 fail_timeout=2;
}

   Nginx的基本配置已完成,其實以上總結的鳳毛菱角,nginx強大功能背後所涉及的配置複雜程度遠非於此,而官網文檔,非常有參考及學習價值,值得經常查閱!

附:

Nginx rpm包下載地址:https://pkgs.org/download/nginx

Tengine官網學習地址:http://tengine.taobao.org/


--- 第三部分完成!



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