nginx服務

 

Nginx

提供web服務,也是工作在應用層的負載均衡器,擁有強大的緩存能力。

本章主要學習,web server、web reverse proxy(http)和cache

緩存服務器使用較多的是varnish+squid:

任何緩存都是反向代理,但是varnish反向代理能力還是與nginx有很大差距。所以,varnish還是做緩存服務,而nginx做web代理

與nginx同一級別的反向代理服務器還有haproxy:基于tcp reverse proxy能夠反向代理mysql服務。也支持http的反向代理。是nginx的競爭對手。

nginx服務于靜態內容的能力上比httpd強大很多。

engine X = Nginx

http協議:web服務器(類似于httpd)、http reverse proxy(類似于httpd)、imap/pop3 reverse proxy

NGINX is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server . C10K(10K Connections).  二次發型版 阿里Tengine, OpenResty. 解決10000個并發服務、大并發

http協議:

URL:shceme://username:password@host:port/path;params?query#frag

http事務:

request:
    <method> <URL> <VERSION>
    HEADERS

    <body>

reponse:
    <VERSION> <STATUS> <REASON-PHRASE>
    HEADERS

    <body>

Method:GET/HEAD/POST, PUT/DELETE, TRACES, OPTIONS

Status Code:
            1xx:
            2xx:成功類響應碼,200
            3xx:重定向類的響應碼,301, 302, 304
            4xx:客戶端錯誤,403,404
            5xx:服務器端錯誤,502

認證:
    基于ip認證
    基于用戶認證 

httpd MPM:
    prefork:進程模型,兩級結構,主進程master負責生成子進程,每個子進程負責響應一個請求;
    worker:線程模型,三級結構,主進程master負責生成子進程,每個子進程負責生成多個線程,每個線程響應一個請求;
    event:主進程master負責生成子進程,每個子進程響應多個請求;

I/O模型:

用戶空間進程發起系統調用,要讀取硬盤上的數據。內核代為執行,內核要將數據讀取并轉交給用戶空間進程,也必須先從硬盤上讀取,將數據載 入內核的內存空間,之后再將內核內存中的數據復制到用戶空間進程的空間中。 用戶空間進程–發起系統調用–內核從硬盤上讀取數據–讀取到內核的空間–將內核空間的數據復制給用戶進程的內存空間中。

進程運行中,感知不到其他進程的存在,只是知道內核,和自己 用戶空間進程,運行在線性內存中。

每一次IO分為兩步,先將數據讀取到內核內存,再將數據復制給客戶空間進程 單只從內核內存復制到,進程空空間的這個階段才是IO發生的過程。

nginx 支持事件驅動異步IO,內存映射

阻塞型、非阻塞型、復用型、信號驅動型、異步

同步/異步:
        關注消息通知機制;

        消息通知:
            同步:等待對方返回消息; 
            異步:被調用者通過狀態、通知或回調機制通知調用者-被調用者的運行狀態;(也就上是不用等待,有消息了會告訴你)

            回調,將進程調度回來

            通知,僅僅是通知。告訴你飯好了。
                有一個公共顯示屏顯示,調用的結果。
                    只是在顯示屏上顯示一次(邊緣觸發)
                    如果發了一次,調用者還是沒有回來,就再發一次(水平觸發)
                使用電子公告牌的好處是,進程要了多個系統調用,但是進程是阻塞在哪個上好呢,顯然阻塞在哪個上也不合適
                所以阻塞在電子公告牌上比較合適,阻塞一個上就可以兼顧多個調用了。

阻塞/非阻塞:
    關注調用者在等待結果返回之前所處的狀態; 

        阻塞:blocking,調用結果返回之前,調用者被掛起;(處于不可中斷睡眠狀態)

        非阻塞:nonblocking,調用結果返回之前,調用者不會被掛起;
            當內核去讀取硬盤上的數據時,進程是不被阻塞的,處于忙等待狀態。當內核往進程內存中寫入數據時才被阻塞(但是相對第一階段的時間會短的多,因為內核要用進程的空間進程被阻塞)

    一次IO請求,都會由兩階段組成:
        第一步:等待數據,即數據從磁盤到內核內存; 
        第二步:復制數據,即數據內核內存到進程內存;

復用型IO調用:

不被一個系統調用而阻塞在IO上,使用電子公告牌的功能。而是阻塞在電子公告牌上。 nginx使用的是異步非阻塞IO(非阻塞+復用IO調用) nginx事件驅動非阻塞

解決方案

    prefork機制
        select():1024
        poll():

    event-driven:
            epoll(Linux):libevent
            Kqueue(BSD):
            Solaris:/dev/poll

NGINX is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. NGINX is known for its high performance, stability, rich feature set, simple configuration, and low resource consumption.

NGINX is one of a handful of servers written to address the C10K problem. Unlike traditional servers, NGINX doesn’t rely on threads to handle requests. Instead it uses a much more scalable event-driven (asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load. Even if you don’t expect to handle thousands of simultaneous requests, you can still benefit from NGINX’s high-performance and small memory footprint. NGINX scales in all directions: from the smallest VPS all the way up to large clusters of servers.

NGINX powers several high-visibility sites, such as Netflix, Hulu, Pinterest, CloudFlare, Airbnb, WordPress.com, GitHub, SoundCloud, Zynga, Eventbrite, Zappos, Media Temple, Heroku, RightScale, Engine Yard, MaxCDN and many others.

Nginx的程序架構:

    master/worker
        一個master進程:
            負載加載配置文件、管理worker進程、平滑升級
        一個或多個worker進程(一般等于CPU核心數)
            處理并響應用戶請求

        緩存相關的進程:
            cache loader:載入緩存對象
            cache manager:管理緩存對象

    特性:異步、事件驅動和非阻塞
        并發請求處理:通過kevent/epoll/select
        文件IO:高級IO sendfile(資源部發送給調用者,直接封裝成報文發出),異步,mmapne內存映射(將磁盤上的資源,直接映射進調用者的內容。不需要內核讀取再復制給調用者)

nginx高度模塊塊:高度模塊化,但其模塊早期不支持DSO機制;近期版本支持動態裝載和卸載;

        模塊分類:
            核心模塊:core module
            標準模塊:
                Standard HTTP modules
                Optional HTTP modules
                Mail modules
                Stream modules  tcp/udp協議的反代;可以反向代理mysql服務                                                                                                
            3rd party modules

    nginx的功用:
        靜態的web資源服務器;
        結合FastCGI/uwSGI/SCGI等協議反代動態資源請求;
            具有緩存功能。將動態資源緩存在本地

        http/https協議的反向代理;
        imap4/pop3協議的反向代理;
        tcp/udp協議的反代;可以反向代理mysql服務

nginx的安裝配置:

    官方的預制包:
        http://nginx.org/packages/centos/7/x86_64/RPMS/

    編譯安裝:
        ~]# yum install pcre-devel openssl-devel zlib-devel
        ~]# useradd -r nginx
        ~]#  ./configure --prefix=/usr/local/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.pid --lock-path=/var/run/nginx.lock --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_dav_module --with-http_stub_status_module --with-threads --with-file-aio
        # make && make install

配置:

配置文件的組成部分:
    主配置文件:nginx.conf
    include conf.d/*.conf
    fastcgi, uwsgi,scgi等協議相關的配置文件
    mime.types:支持的mime類型

主配置文件的配置指令:
    directive value [value2 ...];

注意:
    (1) 指令必須以分號結尾;
    (2) 支持使用配置變量;
        內建變量:由Nginx模塊引入,可直接引用;
        自定義變量:由用戶使用set命令定義;
        set variable_name value;
    引用變量:$variable_name

主配置文件結構:

main block:主配置段,也即全局配置段;
    event {
            ...
    }:事件驅動相關的配置;

http {
    ...
}:http/https 協議相關的配置段;

mail {
    ...
}
stream {
    ...
}

http協議相關的配置結構

http {
    ...
    ...:各server的公共配置

server {
        ...
}:每個server用于定義一個虛擬主機;

server {
    ...
    server_name  #服務器主機名
    root         #服務器根,與httpd下的documentroot一樣
    alias        #別名
    location [OPERATOR] URL {   #定義不同url該如何映射
    ...
    if CONDITION {
    ...
            }
        }
    }
}

main配置段常見的配置指令:Core functionality

            分類:
                正常運行必備的配置
                優化性能相關的配置
                用于調試及定位問題相關的配置
                事件驅動相關的配置

正常 運行必備的配置:

1、user
    Syntax: user user [group];
    Default:    user nobody nobody;
    Context:    main

Defines user and group credentials used by worker processes. If group is omitted, a group whose name equals that of user is used.

2、pid /PATH/TO/PID_FILE;
    指定存儲nginx主進程進程號碼的文件路徑;

3、include file | mask;
    指明包含進來的其它配置文件片斷;

4、load_module file;
    指明要裝載的動態模塊;

5、thread_pool
    定義線程池,定義名稱 線程個數,隊列長度,超出隊列的用戶則無法訪問。
    有的請求被因為各種原因,網絡,磁盤IO等... 被阻塞,但是為了不影響其他客戶請求,將其放入線程池中,繼續處理其他請求。

性能優化相關的配置:

1、worker_processes number | auto;
        worker進程的數量;通常應該為當前主機的cpu的物理核心數;

2、worker_cpu_affinity cpumask ...;
   worker_cpu_affinity auto [cpumask];
    worker與CPU的姻親關系,綁定在一起。不進行cpu切換。

        CPU MASK:
            00000001:0號CPU
            00000010:1號CPU
            ... ...
    [root@localhost nginx-1.11.5]# watch -n1 "ps axo pid,comm,psr |grep nginx" #測試cpu切換

3、worker_priority number;
        指定worker進程的nice值,設定worker進程優先級;負數優先級高[-20,20]

4、worker_rlimit_nofile number;
        worker進程所能夠打開的文件數量上限;
    很重要的設定,worker的并發數量高了,這個數值也要調高。

調試、定位問題:

1、daemon on|off;    
        是否以守護進程方式運行Nignx;
    centos6可以不以守護進程方式運行,調試信息會輸出到屏幕。
    但是centos7,使用systemd不適用

2、master_process on|off;
        是否以master/worker模型運行nginx;默認為on;
        以單級架構運行。只對開發人員有用。

3、error_log file [level];
    #可以定義在main, http, mail, stream, server, location

事件驅動相關的配置: 并發響應,有請求就響應 events { … }

1、worker_connections number;
每個worker進程所能夠打開的最大并發連接數數量;

worker_processes * worker_connections是nginx服務的最大并發連接數

2、use method;
指明并發連接請求的處理方法;默認使用epool             
use epoll;

3、accept_mutex on | off;
處理新的連接請求的方法;on意味著由各worker輪流處理新請求,Off意味著每個新請求的到達都會通知所有的worker進程;
互斥鎖,保證一個資源在某一時刻只能被一個線程所使用。
有讀鎖和寫鎖,寫鎖其他進程不能讀取和寫入,讀鎖其他進程可以讀,但是不能寫

if volume of new connections is low, some of the worker processes may just waste system resources.系統負載較低時建議打開,防止系統資源浪費。

你把這粒糧食直接扔到小雞中間,一百只小雞一起上來搶,最終只有一只小雞能得手,其它九十九只小雞只能鎩羽而歸。這就相當于關閉了acceptmutex。 你主動抓一只小雞過來,把這粒糧食塞到它嘴里,其它九十九只小雞對此渾然不知,該睡覺睡覺。這就相當于激活了acceptmutex。

一盆糧食不知何年何月才能喂完,大家可以設想一下幾十只小雞排隊等著喂食時那種翹首以盼的情景。此時更好的方法是把這盆糧食直接撒到小雞中間,讓它們自己去搶,雖然這可能會造成一定程度的混亂,但是整體的效率無疑大大增強了。

Nginx缺省激活了accept_mutex,是一種保守的選擇。如果關閉了它,可能會引起一定程度的驚群問題,表現為上下文切換增多(sar -w)或者負載上升,但是如果你的網站訪問量比較大,為了系統的吞吐量,我還是建議大家關閉它。

http協議的相關配置:ngxhttpcore_module

            http {
                ... ...  ##server的公共配置
                server {
                    ...
                    server_name
                    root
                    location [OPERATOR] /uri/ {
                        ...
                     }
                  }

                server {
                    ...
                  }
                }

1、server { ... }
    配置一個虛擬主機;

    server {
        listen address[:PORT]|PORT;
        server_name SERVER_NAME;
        root /PATH/TO/DOCUMENT_ROOT;
    }

2、listen PORT|address[:port]|unix:/PATH/TO/SOCKET_FILE
    listen address[:port] [default_server] [ssl] [http2 | spdy]  [backlog=number] [rcvbuf=size] [sndbuf=size]

3、server_name name ...;
    指明虛擬主機的主機名稱;后可跟多個由空白字符分隔的字符串;
        支持*通配任意長度的任意字符;server_name *.magedu.com
        支持~起始的字符做正則表達式模式匹配;server_name ~^www\d+\.magedu\.com$

                匹配機制:
                    (1) 首先是字符串精確匹配;
                    (2) 左側*通配符;
                    (3) 右側*通配符;
                    (4) 正則表達式;

練習:定義四個虛擬主機,混合使用三種類型的虛擬主機;
       僅開放給來自于本地網絡中的主機訪問;

回顧:IO模型 、nginx

IO模型:
    阻塞型
    非阻塞型
    復用型(select, poll)
    信號驅動型(epoll, kqueue, /dev/poll)
    AIO

    階段:等待數據準備完成,復制數據;

nginx:master/worker 
    master
    worker(work_connections)
    cache loader
    cache manager

    模塊類別:核心模塊、標準模塊(http標準模塊、http可選模塊、mail模塊、stream模塊)、3rd模塊

nginx.conf
    main block
    event {
        ...
    }
    http {
        ...
        server {
            ...
            server_name
            listen
            root
            location /uri/ {
                ...
            }
        }
        server {
            ...
        }
    }
    stream {

    }

Nginx(2)

        http協議的相關配置:
            http {
                ... ...
                server {
                    ...
                    server_name
                    root
                    location [OPERATOR] /uri/ {
                        ...
                    }
                }
                server {
                    ...
                }
            }

與套接字相關的配置(2)

4、tcp_nodelay on | off;
    在keepalived模式下的連接是否啟用TCP_NODELAY選項;
    keeplive模式下,nginx默認將用戶請求的非常小的資源延遲發送。在長連接還沒有斷開時,再有其他資源請求,隨其他請求一起發送。
    tcp_nodelay on 就是不開啟,只要用戶有請求,不延時直接發送。
    建議直接發送 默認值on即可

5、sendfile on | off;
    是否啟用sendfile功能;
    在內核級別直接封裝用戶請求的資源。

定義路徑相關的配置:

6、root path; 
    設置web資源路徑映射;用于指明用戶請求的url所對應的本地文件系統上的文檔所在目錄路徑;可用的位置:http, server, location, if in location;

    用在http中,為所有虛擬主機提供默認配置的,但是所有的虛擬主機server也可以配置,server中的配置覆蓋http中的配置。

    nginx中的root 與location中的 / 是一個意義。也就root就是rul的根,location中使用的 / 是一個意思。
    root /var/www/html 的意思等于 location /

實例:1  root 和location中 / d 關系

        server {
            root /var/www/html
        }

    與 在location中
    server {
        location / {
            root /var/www/html
        }
    }
    上面兩種寫法的效果是一樣的。

實例2 location /admin/ 容器中定義了root

    server {
        server_name www.magedu.com;
        root /var/www/html/;

        location /admin/ {
            root /webapps/app1/data/;
        }
    }

    意義:虛擬機主機的根為 /var/www/html/下
        http://wwww.magedu.com/的根是/var/www/html/

        location中/admin/ 指的是http://wwww.magedu.com/admin/
        資源路徑 /webapps/app1/data/路徑下的admin目錄

實例3 location /admin/ 沒有定義root

    server {
        root /var/www/html/;
        server_name www.magedu.com;

        location /admin/ {
            ...
        }
    }

    意義:location中定義的/admin/ 指的是/var/www/html/admin/

        http://wwww.magedu.com/admin/
        資源路徑/var/www/html/admin

7、location

location [ = | ~ | ~* | ^~ ] uri { … }

location @name { … }

Context:server, location    

    在一個server中location配置段可存在多個,用于實現從uri到文件系統的路徑映射;ngnix會根據用戶請求的URI來檢查定義的所有location,并找出一個最佳匹配,而后應用其配置;

    httpd中的location和director分別是站在url和文件系統角度的。
    nginx中location也是站在url的角度的。

    =:對URI做精確匹配;例如, http://www.magedu.com/, http://www.magedu.com/index.html
            location = / {
                    ...
            }

    ~:對URI做正則表達式模式匹配,區分字符大小寫;
    ~*:對URI做正則表達式模式匹配,不區分字符大小寫;
    ^~:對URI的左半部分做匹配檢查,不區分字符大小寫;
    不帶符號:匹配起始于此uri的所有的url;

匹配優先級:=, ^~, ~/~*,不帶符號;

官方文檔是咧

Let’s illustrate the above by an example:

location = / {     ###精確匹配整個url
    [ configuration A ]
}

location / {
    [ configuration B ]
}
            ##訪問http://magedu.com和訪問http://magedu.com/index.html 效果是不一樣的。
------------------------------------------------------------------------
location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {     ###the “/images/1.gif” request will match configuration D 
    [ configuration D ]    ###匹配請求資源的資源的左側的url
}

location ~* \.(gif|jpg|jpeg)$ {   ###匹配以.(gif|jpg|jpeg)結尾的url
    [ configuration E ]
}
The “/” request will match configuration A, the “/index.html” request will match configuration B, the “/documents/document.html” request will match configuration C, the “/images/1.gif” request will match configuration D, and the “/documents/1.jpg” request will match configuration E.

alias path; 只能用于location中

    定義路徑別名,文檔映射的另一種機制;僅能用于location上下文;

        注意:location中使用root指令和alias指令的意義不同;
            (a) root,給定的路徑對應于location中的/uri/左側的/;
                    資源位置是root定義目錄下的uri目錄

            (b) alias,給定的路徑對應于location中的/uri/右側的/;
                /uri/的根 資源映射位置是別名指定的位置

index file …;

是由一個獨立的模塊提供的指令。ngx_http_index_module 標準模塊
Syntax: index file ...;  ##可以根多個文件名,定義默認主頁
Default:    
index index.html;
Context:    http, server, location

    默認資源;http, server, location;

error_page code … [=[response]] uri;

定義顯示給用戶的錯誤頁面顯示。

Syntax: error_page code ... [=[response]] uri;
Default:    —
Context:    http, server, location, if in location

=[response 自定義錯誤響應碼,例如可以將200設置成響應碼。

Defines the URI that will be shown for the specified errors.

11、try_files file … uri;

定義客戶端請求的相關配置

12、keepalive_timeout timeout [header_timeout];
    設定保持連接的超時時長,0表示禁止長連接;默認為75s;

13、keepalive_requests number;
    在一次長連接上所允許請求的資源的最大數量,默認為100; 

14、keepalive_disable none | browser ...;
    對哪種瀏覽器禁用長連接;

15、send_timeout time;

Syntax: send_timeout time;
Default:    
send_timeout 60s;
Context:    http, server, location

    向客戶端發送響應報文的超時時長,此處,是指兩次寫操作之間的間隔時長;
    這里的寫是指對nginx監聽的套接字的寫,想用戶發送信息。   
服務端已經發出了第一個報文,超過了60秒客戶端還是沒有接收到就斷開連接。

16、client_body_buffer_size size;  #內存中的緩存
Context:    http, server, location
    用于接收客戶端請求報文的body部分的緩沖區大小;默認64位系統為16k;超出此大小時,其將被暫存到磁盤上的由client_body_temp_path指令所定義的位置;
    如果客戶端通過post等方式發送過來的數據較大,就得先緩存下來在響應。

17、client_body_temp_path path [level1 [level2 [level3]]];

Syntax: client_body_temp_path path [level1 [level2 [level3]]];
Default:    
client_body_temp_path client_body_temp;
Context:    http, server, location
    設定用于存儲客戶端請求報文的body部分的臨時存儲路徑及子目錄結構和數量;定義索引的層級

        16進制的數字;

            client_body_temp_path path  /var/tmp/client_body  1 2 2
            表示16個一級子目錄, 每個一級子目錄有256個二級子目錄,每個二級子目錄下有256個三級子目錄
            數字表示幾個十六進制數字。2個16進制表示265個(0-255) FF=255
設置的目錄nginx要有讀寫權限。

對客戶端進行限制的相關配置:

18、limit_rate rate;
    限制響應給客戶端的傳輸速率,單位是bytes/second,0表示無限制;

19、limit_except method ... { ... }
    限制對指定的請求方法之外的其它方法的使用客戶端;

    limit_except GET {
        allow 192.168.1.0/32;
        deny  all;
    }
除了get之外的其他方法僅允許192.168.1.0/32這個網絡訪問。

文件操作優化的配置

20、aio on | off | threads[=pool];
    是否啟用aio功能;異步IO模型

21、directio size | off;
    在Linux主機啟用O_DIRECT標記,此處意味文件大于等于給定的大小時使用,例如directio 4m;大于4m的直接讀取發往進程,或直接寫入磁盤,這樣的數據不適用緩存或緩沖區。

22、openfilecache off;  打開文件緩存

    Context:    http, server, location

    open_file_cache max=N [inactive=time];
        nginx可以緩存以下三種信息:
            (1) 文件的描述符、文件大小和最近一次的修改時間;
            (2) 打開的目錄結構;
            (3) 沒有找到的或者沒有權限訪問的文件的相關信息;

        max=N:可緩存的緩存項上限;達到上限后會使用LRU算法實現緩存管理;

        inactive=time:緩存項的非活動時長,在此處指定的時長內未被命中的或命中的次數少于open_file_cache_min_users指令所指定的次數的緩存項即為非活動項;
        通過用戶自定定義超時時間(指定時間沒有訪問過)和非活動狀態(少于用戶定義的訪問次數)

23、open_file_cache_valid time;
    緩存項有效性的檢查頻率;默認為60s; 

24、open_file_cache_min_uses number;
    在open_file_cache指令的inactive參數指定的時長內,至少應該被命中多少次方可被歸類為活動項;

25、open_file_cache_errors on | off;
    是否緩存查找時發生錯誤的文件一類的信息;

ngxhttpaccess_module模塊:

    通常在location中使用,實現基于ip的訪問控制功能

allow address | CIDR | unix: | all;
deny address | CIDR | unix: | all;

http, server, location, limit_except

ngxhttpauthbasicmodule模塊

實現基于用戶的訪問控制,使用basic機制進行用戶認證;

28、auth_basic string | off;
29、auth_basic_user_file file;

    location /admin/ {
        alias /webapps/app1/data/;
        auth_basic "Admin Area"; #彈出對話框的提示信息
        auth_basic_user_file /etc/nginx/.ngxpasswd;
    }

    注意:htpasswd命令由httpd-tools所提供;

[root@localhost ~]# htpasswd  -c -m ./test tom
New password:
Re-type new password:
Adding password for user tom
[root@localhost ~]# htpasswd   -m ./test jery
New password:
Re-type new password:
Adding password for user jery
[root@localhost ~]# cat test
tom:$apr1$O0R/I7.P$9cvGp1HCdLhITaJYCPsVm/
jery:$apr1$WYavczT5$ADlzWUjawkT7WskfDs21L/

ngxhttpstubstatusmodule模塊

    用于輸出nginx的基本狀態信息;

    Active connections: 291 
    server accepts handled requests
        16630948 16630948 31070465 
    Reading: 6 Writing: 179 Waiting: 106    

    Active connections: 活動狀態的連接數;
    accepts:已經接受的客戶端請求的總數;
    handled:已經處理完成的客戶端請求的總數;
    requests:客戶端發來的總的請求數;
    Reading:處于讀取客戶端請求報文首部的連接的連接數;
    Writing:處于向客戶端發送響應報文過程中的連接數;
    Waiting:處于等待客戶端發出請求的空閑連接數;

這些信息可以導入到zibx中,監控nginx。通常需要自己寫腳本將信息導入到zibx中。

30、stub_status;

    配置示例:
        location  /basic_status {
                stub_status;
        }

ngxhttplog_module模塊

    he ngx_http_log_module module writes request logs in the specified format.

可以單獨定義某開個location或server中,記錄或不記錄日志。

31、log_format name string ...;
    string可以使用nginx核心模塊及其它模塊內嵌的變量;
    定義combine格式

32、access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
        fomat 指的是log_format定義定name

    access_log off; ##可以單獨定義某開個location或server中,記錄或不記錄日志。

    訪問日志文件路徑,格式及相關的緩沖的配置;
        buffer=size
        flush=time  每隔多長時間同步一次數據到磁盤上。

33、open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
    open_log_file_cache off;
        緩存各日志文件相關的元數據信息;
        nginx用戶大量訪問,或調試日志開啟,會產生大量日志,方便用產看日志信息。

            max:緩存的最大文件描述符數量;
            min_users:在inactive指定的時長內訪問大于等于此值方可被當作活動項;
            inactive:非活動時長;
            valid:驗正緩存中各緩存項是否為活動項的時間間隔;

課外作業:為nginx定義使用類似于httpd的combined格式的訪問日志;

回顧: nginx.conf配置文件: http { … server { … location /URI/ { … } … } … }

    ngx_http_core_module模塊:
        limit_rate, limit_except, aio, directio, open_file_cache, send_timeout, client_body_buffer_size, client_body_temp_path, ...

    ngx_http_access_module:
        allow, deny 

    ngx_http_auth_basic_module:
        auth_basic
        auth_basic_user_file

    ngx_http_log_module:
        log_format
        access_log
        open_log_file_cache 

    ngx_http_stub_status_module:
        stub_status

Nginx(3)

ngxhttprewrite_module模塊:

The ngx_http_rewrite_module module is used to change request URI using PCRE regular expressions, return redirects, and conditionally select configurations.
將用戶請求的URI基于regex所描述的模式進行檢查,而后完成替換;

1、rewrite regex replacement [flag]

將用戶請求的URI基于regex所描述的模式進行檢查,匹配到時將其替換為replacement指定的新的URI;

注意:如果在同一級配置塊中存在多個rewrite規則,那么會自下而下逐個檢查;被某條件規則替換完成后,會重新一輪的替換檢查,因此,隱含有循環機制;[flag]所表示的標志位用于控制此循環機制;

如果replacement是以http://或https://開頭,則替換結果會直接以重向返回給客戶端;
    301:永久重定向;

[flag]:
    last:重寫完成后停止對當前URI在當前location中后續的其它重寫操作,而后對新的URI啟動新一輪重寫檢查;提前重啟新一輪循環; 
    break:重寫完成后停止對當前URI在當前location中后續的其它重寫操作,而后直接跳轉至重寫規則配置塊之后的其它配置;結束循環;
    redirect:重寫完成后以臨時重定向方式直接返回重寫后生成的新URI給客戶端,由客戶端重新發起請求;不能以http://或https://開頭;
    permanent:重寫完成后以永久重定向方式直接返回重寫后生成的新URI給客戶端,由客戶端重新發起請求;

2、return

return code [text];
return code URL;
return URL;

Stops processing and returns the specified code to a client.

3、 rewrite_log on | off;

是否開啟重寫日志;

4、 if (condition) { … }

引入一個新的配置上下文 ;條件滿足時,執行配置塊中的配置指令;server, location;

condition:
    比較操作符:
        ==
        !=
        ~:模式匹配,區分字符大小寫;
        ~*:模式匹配,不區分字符大小寫;
        !~:模式不匹配,區分字符大小寫;
        !~*:模式不匹配,不區分字符大小寫;
    文件及目錄存在性判斷:
        -e, !-e
        -f, !-f
        -d, !-d
        -x, !-x

5、set $variable value;

用戶自定義變量 ;

ngxhttpgzip_module:

The ngx_http_gzip_module module is a filter that compresses responses using the “gzip” method. This often helps to reduce the size of transmitted data by half or even more.

1、gzip on | off;
    Enables or disables gzipping of responses.

2、gzip_comp_level level;
    Sets a gzip compression level of a response. Acceptable values are in the range from 1 to 9.

3、  gzip_disable regex ...;
    Disables gzipping of responses for requests with “User-Agent” header fields matching any of the specified regular expressions.

4、  gzip_min_length length;
    啟用壓縮功能的響應報文大小閾值; 

5、gzip_buffers number size;
    支持實現壓縮功能時為其配置的緩沖區數量及每個緩存區的大小;

6、gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any ...;
    nginx作為代理服務器接收到從被代理服務器發送的響應報文后,在何種條件下啟用壓縮功能的;
        off:對代理的請求不啟用
        no-cache, no-store,private:表示從被代理服務器收到的響應報文首部的Cache-Control的值為此三者中任何一個,則啟用壓縮功能;

7、gzip_types mime-type ...;
    壓縮過濾器,僅對此處設定的MIME類型的內容啟用壓縮功能;

ngxhttpfastcgi_module模塊:

The ngx_http_fastcgi_module module allows passing requests to a FastCGI server.

1、fastcgi_pass address;
    address為fastcgi server的地址;  location, if in location;

2、fastcgi_index name;
    fastcgi默認的主頁資源; 

3、fastcgi_param parameter value [if_not_empty];
    Sets a parameter that should be passed to the FastCGI server. The value can contain text, variables, and their combination.

配置示例1:
        前提:配置好fpm server和mariadb-server服務;
            location ~* \.php$ {
                root           /usr/share/nginx/html;
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html$fastcgi_script_name;
                include        fastcgi_params;
            }

配置示例2:通過/pm_status和/ping來獲取fpm server狀態信息;
        location ~* ^/(pm_status|ping)$ {
            include        fastcgi_params;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param  SCRIPT_FILENAME  $fastcgi_script_name;
        }           

4、fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];

    定義fastcgi的緩存;緩存位置為磁盤上的文件系統,由path所指定路徑來定義;

        levels=levels:緩存目錄的層級數量,以及每一級的目錄數量;levels=ONE:TWO:THREE
            leves=1:2:2
        keys_zone=name:size
            k/v映射的內存空間的名稱及大小
        inactive=time
            非活動時長
        max_size=size
            磁盤上用于緩存數據的緩存空間上限

5、fastcgi_cache zone | off;
    調用指定的緩存空間來緩存數據;http, server, location

6、fastcgi_cache_key string;
    定義用作緩存項的key的字符串;

7、fastcgi_cache_methods GET | HEAD | POST ...;
    為哪些請求方法使用緩存;

8、fastcgi_cache_min_uses number;
    緩存空間中的緩存項在inactive定義的非活動時間內至少要被訪問到此處所指定的次數方可被認作活動項;

9、fastcgi_cache_valid [code ...] time;
    不同的響應碼各自的緩存時長;

示例: http { … fastcgicachepath /var/cache/nginx/fastcgicache levels=1:2:1 keyszone=fcgi:20m inactive=120s; … server { … location ~* .php$ { … fastcgicache fcgi; fastcgicachekey $requesturi; fastcgicachevalid 200 302 10m; fastcgicachevalid 301 1h; fastcgicachevalid any 1m; … } … } … }

10、fastcgikeepconn on | off;

            By default, a FastCGI server will close a connection right after sending the response. However, when this directive is set to the value on, nginx will instruct a FastCGI server to keep connections open.

ngxhttpssl_module模塊:

    1、  ssl on | off;
        Enables the HTTPS protocol for the given virtual server.

    2、ssl_certificate file;
        當前虛擬主機使用PEM格式的證書文件;

    3、ssl_certificate_key file;
        當前虛擬主機上與其證書匹配的私鑰文件;

    4、ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];
        支持ssl協議版本,默認為后三個;

    5、ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
        builtin[:size]:使用OpenSSL內建的緩存,此緩存為每worker進程私有;

        [shared:name:size]:在各worker之間使用一個共享的緩存;

    6、ssl_session_timeout time;
        客戶端一側的連接可以復用ssl session cache中緩存 的ssl參數的有效時長;

    配置示例:
        server {
            listen 443 ssl;
            server_name www.magedu.com;
            root /vhosts/ssl/htdocs;
            ssl on;
            ssl_certificate /etc/nginx/ssl/nginx.crt;
            ssl_certificate_key /etc/nginx/ssl/nginx.key;
            ssl_session_cache shared:sslcache:20m;
        }

ngxhttpreferer_module模塊:

    The ngx_http_referer_module module is used to block access to a site for requests with invalid values in the “Referer” header field. 

    1、valid_referers none | blocked | server_names | string ...;
        定義referer首部的合法可用值;

            none:請求報文首部沒有referer首部;
            blocked:請求報文的referer首部沒有值;
            server_names:參數,其可以有值作為主機名或主機名模式;
                arbitrary_string:直接字符串,但可使用*作通配符;
                regular expression:被指定的正則表達式模式匹配到的字符串;要使用~打頭,例如 ~.*\.magedu\.com;

        配置示例:
            valid_referers none block server_names *.magedu.com *.mageedu.com magedu.* mageedu.* ~\.magedu\.;

            if($invalid_referer) {
                return 403;
            }

博客作業:以上所有內容;
練習:實現lnmp,提供多個虛擬主機;
    (1) http, 提供wordpress;
    (2) https, 提供pma;

回顧: Nginx: gzip、ssl、fastcgi、referer、…

LB Cluster:lvs
    硬件:F5 BIG-IP,Citrix NetScaler,A10 A10
    軟件:lvs, nginx, haproxy, pound, ats, perlbal

    傳輸層:lvs, nginx(stream), haproxy(mode tcp)
    應用層:nginx(upstream),harproxy(mode http), httpd(balancer), ats, perlbal, pound, mysql-proxy, ...

    lvs:
        靜態方法:rr, wrr, sh, dh
        動態方法:lc, wlc, sed, nq, lblc, lblcr

    session保持:
        session sticky
        session replication 
        session server(memcached, redis)

Nginx(4)

LB Cluster:
    傳輸層:lvs、nginx、haproxy
    應用層:nginx(http, https, smtp, pop, imap), haproxy(http), httpd(http/https), ats, perlbal, pound, ...

nginx load balancer:
    tcp/udp

nginx proxy:
    reverse proxy:

應用程序發布:
    灰度模型:
        (1) 如果存在用戶會話;
            從服務器上拆除會話;
        (2) 新版本應用程序存在bug;
            回滾;

正向代理類似于DNAT,反向代理類似SNAT

ngxhttpproxy_module  #http的反代模塊 首先是代理其次才是緩存 透傳式代理才有緩存功能,類似DNS的遞歸查詢 客戶端是看不到后端服務的。代理服務器首先是代理,其次才是緩存服務器。代理服務器先找自己的緩存,沒有才找后端主機請求。 代理服務器不一定都有緩存

旁掛式或旁路式緩存,請求者先找緩存,沒有的話才找真實服務器 客戶端先訪問緩存服務器,緩存服務器沒有才找真實服務器。

(1) proxy_pass URL;
        location, if in location, limit_except

        注意:proxy_pass后面的路徑不帶uri時,其會將location的uri傳遞給后端主機;

            location /uri/ {
                proxy_pass http://HOST;
            }

        proxy_pass后面的路徑是一個uri時,其會將location的uri替換為proxy_pass的uri;
            location /uri/ {
                proxy_pass http://HOST/new_uri/;
            }

        如果location定義其uri時使用正則表達式的模式,則proxy_pass之后必須不能使用uri;
            location ~|~* PATTERN {
                proxy_pass http://HOST;
            }

(2) proxy_set_header field value;
        設定發往后端主機的請求報文的請求首部的值; 

        示例:
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for

(3) proxy_cache_path

        proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];

(4) proxy_cache zone | off;
        調用的緩存的名稱,或禁用緩存;

(5) proxy_cache_key string;
        緩存條目的鍵;

(6) proxy_cache_valid [code ...] time;
        對各類響應碼的緩存時長;

    使用示例:
        定義在http{}中:
            proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2:1 keys_zone=pcache:10m max_size=1g;

        定義在server{}及其內部的組件中:
            proxy_cache pcache;
            proxy_cache_key $request_uri;
            proxy_cache_valid 200 302 10m;
            proxy_cache_valid 301 1h;
            proxy_cache_valid any 1m;               

(7) proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off ...;

(8)     proxy_connect_timeout
        proxy_read_timeout
        proxy_send_timeout

(9)   proxy_buffer_size
        proxy_buffering
        proxy_buffers

ngxhttpheaders_module

    The ngx_http_headers_module module allows adding the “Expires” and “Cache-Control” header fields, and arbitrary fields, to a response header.

(1) add_header name value [always];
        向響應報文中添加自定義首部;

        可用上下文:http, server, location, if in location

        add_header X-Via $server_addr;
        add_header X-Accel $server_name;

(2) expires [modified] time;
        expires epoch | max | off;

        用于定義Expire或Cache-Control首部的值,或添加其它自定義首部;

回顧: nginx: web server http/https reverse proxy tcp/udp upstream server

ngx_http_proxy_module
    proxy_pass 
    proxy_set_header

    proxy_cache_path

    proxy_cache
    proxy_cache_key
    proxy_cache_valid

    proxy_connect_timeout, proxy_read_timeout, proxy_send_timeout

ngx_http_headers_module
    add_header

Nginx(5)

ngxhttpupstream_module模塊

    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.

    1、upstream name { ... }
        定義后端服務器組,會引入一個新的上下文;Context: http

        upstream httpdsrvs {
            server ...
            server...
            ...
        }

    2、server address [parameters];
        在upstream上下文中server成員,以及相關的參數;Context:  upstream

        address的表示格式:
            unix:/PATH/TO/SOME_SOCK_FILE
            IP[:PORT]
            HOSTNAME[:PORT]

        parameters:
            weight=number
                權重,默認為1;
            max_fails=number
                失敗嘗試最大次數;超出此處指定的次數時,server將被標記為不可用;
            fail_timeout=time
                設置將服務器標記為不可用狀態的超時時長;
            max_conns
                當前的服務器的最大并發連接數;
            backup
                將服務器標記為“備用”,即所有服務器均不可用時此服務器才啟用;
            down
                標記為“不可用”;

    3、least_conn;
        最少連接調度算法,當server擁有不同的權重時其為wlc;

    4、  ip_hash;
        源地址hash調度方法;

    5、hash key [consistent];
        基于指定的key的hash表來實現對請求的調度,此處的key可以直接文本、變量或二者的組合;

        作用:將請求分類,同一類請求將發往同一個upstream server;

        If the consistent parameter is specified the ketama consistent hashing method will be used instead.

        示例:
            hash $request_uri consistent;
            hash $remote_addr;

    6、keepalive connections;
        為每個worker進程保留的空閑的長連接數量;

nginx的其它的二次發行版:
    tengine
    OpenResty

ngxstreamcore_module模塊

    模擬反代基于tcp或udp的服務連接,即工作于傳輸層的反代或調度器;

    1、stream { ... }
        定義stream相關的服務;Context:main

        stream {
            upstream sshsrvs {
                server 192.168.22.2:22; 
                server 192.168.22.3:22; 
                least_conn;
            }

            server {
                listen 10.1.0.6:22022;
                proxy_pass sshsrvs;
            }
        }   

    2、listen
        listen address:port [ssl] [udp] [proxy_protocol] [backlog=number] [bind] [ipv6only=on|off] [reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];


博客作業:以上所有內容;

思考:
    (1) 動態資源存儲一組服務器、圖片資源存在一組服務器、靜態的文本類資源存儲在一組服務器;如何分別調度?
    (2) 動態資源基于fastcgi或http協議(ap)?
        lnamp

原創文章,作者:yyw,如若轉載,請注明出處:http://www.www58058.com/56568

(0)
yywyyw
上一篇 2016-11-01
下一篇 2016-11-01

相關推薦

  • linux系統上命令使用格式及常見命令

    [root@localhost ~]# date -d ‘2017-07-06 00:00:00 ‘  用上面這條指令講解命令使用格式 date command  -d 是參數,參數有可選參數,必選參數,在參數前必選加上- ,還是以這條指令為列,-d可以寫成–date,如果寫成date,date前面必選…

    Linux干貨 2017-08-19
  • 正則表達式

    正則表達式:             由一類特殊字符及文本字符所編寫的模式,其中有些字符(元字符)不表示字符            字面意義,而表示控制或通配的功能程序支持:  grep,sed,awk,vim,less…

    2017-08-05
  • 第七周-磁盤管理、RAID及Shell腳本練習

    一、創建一個10G分區,并格式為ext4文件系統; (1)、 要求其block大小為2048, 預留空間百分比為2, 卷標為MYDATA, 默認掛載屬性包含acl; (2)、掛載至/data/mydata目錄,要求掛載時禁止程序自動運行,且不更新文件的訪問時間戳; [root@N1 ~]# mkfs.ext4 -b 2048 -m 2 -L MYDATA /…

    Linux干貨 2017-08-13
  • 下載編譯安裝httpd 2.4最新版本

    關于這個問題分三步講:1.下載最新版本;2.編譯;3.安裝 一:下載httpd 2.4的最新版本:(這里以Centos 7為例,Centos 6里用的是2.2版本的) 下載的話如何找下載路徑—–>下載后是存在windows下,如何將其移進linux中  1.下載路徑: 當然我們現在只要是碰到不會或者不知道的東西,通常會…

    2017-08-26
  • 馬哥教育網絡班21期+第10周課程練習

    1、請詳細描述CentOS系統的啟動流程(詳細到每個過程系統做了哪些事情)     1)開機后會進行POST(開機加電自檢),加載BIOS,之后會根據BIOS上的boot  sequence(引導加載次序)找到第一個有引導程序的設備,找到MBR,bootloader(引導加載器)就安裝在MBR內。M…

    Linux干貨 2016-09-19
  • apache編譯安裝

    apache是什么:     Apache是世界使用排名第一的Web服務器軟件。它可以運行在幾乎所有廣泛使用的計算機平臺上,由于其跨平臺和安全性被廣泛使用,是最流行的Web服務器端軟件之一。它快速、可靠并且可通過簡單的API擴充,將Perl/Python等解釋器編譯到服務器中。同時Apache音譯為阿帕奇,是北美印第安…

    Linux干貨 2016-08-24
欧美性久久久久