nginx

http

  • 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).
  • http協議:
    URL:shceme://username:password@host:port/path;params?query#frag

    • DocumentRoot:/PATH/TO/SOMEDIR/
      Location:URL
    • Alias

    • params:key=value&key=value

    • query:field=value, …

  • http事務:

    • request:

      <method> <URL> <VERSION>
        HEADERS
      
        <body>
    • response:

      <VERSION> <STATUS> <REASON-PHRASE>
        HEADERS
      
        <body>
    • Method:GET/HEAD/POST, PUT/DELETE, TRACE, OPTIONS

    • Status Code:

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

      • 基于ip認證
        基于用戶認證 :basic/digest
    • httpd MPM:

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

I/O模型

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

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

    • 消息通知:
      同步:等待對方返回消息;
      異步:被調用者通過狀態、通知或回調機制通知調用者被調用者的運行狀態;
  • 阻塞/非阻塞:關注調用者在等待結果返回之前所處的狀態;

    • 阻塞:blocking,調用結果返回之前,調用者被掛起;
    • 非阻塞:nonblocking,調用結果返回之前,調用者不會被掛起;
  • 一次IO請求,都會由兩階段組成:

    • 第一步:等待數據,即數據從磁盤到內核內存;
    • 第二步:復制數據,即數據內核內存到進程內存;

    • 阻塞型IO:兩段都是阻塞

    • 非阻塞型IO:第一步非阻塞,第二步阻塞

    • 復用型IO調用:一個進程調用多路IO時,被阻塞在IO復用器上;

      • select():1024 最大并發數
      • poll():
    • 信號驅動型:

      1. 第一步不再阻塞,是異步非阻塞,第二步阻塞;
      2. 第一步不參與,第二步參與;
      • event-driven:
        epoll(Linux):libevent(可提供網絡IO庫)
        Kqueue(BSD):
        /dev/poll(Solaris)
    • 異步:第一步和第二步都不再參與;

nginx的程序架構:

  • master/worker

    • 一個master進程:負載加載和分析配置文件、管理worker進程、平滑升級
    • 一個或多個worker進程:處理并響應用戶請求
    • 作為反代服務器時,緩存相關的進程:

      • cache loader:載入緩存對象
      • cache manager:管理緩存對象
  • 特性:異步、事件驅動和非阻塞

    • 并發請求處理:通過epoll/select
    • 文件IO:高級IO sendfile,異步(AIO),mmap(內存映射)
  • nginx模塊:高度模塊化,但其模塊早期不支持DSO機制;近期版本支持動態裝載和卸載;

    • 核心模塊:core module
    • 標準模塊:

      • HTTP modules:

        • Standard HTTP modules
          Optional HTTP modules
      • Mail modules
      • Stream modules:傳輸層代理
    • 3rd party modules
  • nginx的功用:

    • 靜態的web資源服務器;(圖片服務器,或js/css/html/txt等靜態資源服務器)
    • 結合FastCGI/uwSGI/SCGI等協議反代動態資源請求;
    • http/https協議的反向代理;
    • imap4/pop3協議的反向代理;
    • tcp/udp協議的請求轉發;

nginx的安裝配置:

  • 官方的預制包:

    http://nginx.org/packages/centos/7/x86_64/RPMS/
      Fedora-EPEL:
  • 編譯安裝:

    ~]# yum groupinstall "Development Tools" "Server Platform Development"
      ~]# 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
      ~]# ~]# cat /usr/lib/systemd/system/nginx.service    設置開機啟動
    
      nginx -V    可查看configure的使用選項
  • 程序環境

    • 配置文件的組成部分:

      • 主配置文件:nginx.conf
        include conf.d/*.conf
      • fastcgi, uwsgi,scgi等協議相關的配置文件
      • mime.types:支持的mime類型
    • 主程序文件:/usr/sbin/nginx
    • Unit File:nginx.service
  • 配置:

    • 主配置文件的配置指令:

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

      main block:主配置段,也即全局配置段;
        event {
            ...
        }:事件驅動相關的配置;
      http {
        ...
      }:http/https 協議相關的配置段;
      mail {
        ...
      }
      stream {
        ...
      }
    • http協議相關的配置結構
      nginx沒有中心主機一說,就算是只有一個主機,也是虛擬主機;

      http {
        ...
        ...:各server的公共配置
        server {
            ...
        }:每個server用于定義一個虛擬主機;
        server {
            ...
            listen 
            server_name
            root
            alias
            location [OPERATOR] URL {
                ...
                if CONDITION {
                    ...
                }
            }
        }
      }

配置指令

  • main配置段常見的配置指令:

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

    • 正常運行必備的配置:

      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;
        指明要裝載的動態模塊;

    • 性能優化相關的配置:

      1. worker_processes number | auto;

        • worker進程的數量;通常應該等于小于當前主機的cpu的物理核心數;
        • auto:當前主機物理CPU核心數;
      2. worker_cpu_affinity cpumask …;
        worker_cpu_affinity auto [cpumask];

        • CPU MASK:

          00000000:
            00000001:0號CPU
            00000010:1號CPU
            ... ...
      3. worker_priority number;
        指定worker進程的nice值,設定worker進程優先級;[-20,20]

      4. worker_rlimit_nofile number;
        worker進程所能夠打開的文件數量上限;

    • 調試、定位問題:

      1. daemon on|off;
        是否以守護進程方式運行Nignx;

      2. master_process on|off;
        是否以master/worker模型運行nginx;默認為on;

      3. error_log file [level];

    • 事件驅動相關的配置:

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

        所以,整個nginx所能打開的最大并發連接數:worker_processes * worker_connections

      2. use method;
        指明并發連接請求的處理方法;use epoll;

      3. accept_mutex on | off;
        處理新的連接請求的方法;on意味著由各worker輪流處理新請求,off意味著每個新請求的到達都會通知所有的worker進程;

  • http協議的相關配置:

    http {
          ... ...
          server {
              ...
              server_name
              root
              location [OPERATOR] /uri/ {
                  ...
              }
          }
          server {
              ...
          }
      }
    • 與套接字相關的配置:

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

        server {
         listen address[:PORT]|PORT;
         server_name SERVER_NAME;
         root /PATH/TO/DOCUMENT_ROOT;        指本地文件系統路徑代表的是web服務器
        
         proxy_pass http://172.16.251.168;        指代理指令表示是反代服務器
        }
      2. Listen

        listen PORT|address[:port]|unix:/PATH/TO/SOCKET_FILE
         listen address[:port] [default_server] [ssl] [http2 | spdy]  [backlog=number] [rcvbuf=size] [sndbuf=size]
        • default_server:設定為默認虛擬主機;
          ssl:限制僅能夠通過ssl連接提供服務;
          backlog=number:后援隊列長度;
          rcvbuf=size:接收緩沖區大?。?br /> sndbuf=size:發送緩沖區大??;
      3. server_name name …;

        • 指明虛擬主機的主機名稱;后可跟多個由空白字符分隔的字符串;

          支持*通配任意長度的任意字符;server_name *.magedu.com  www.magedu.*
          支持~起始的字符做正則表達式模式匹配;server_name ~^www\d+\.magedu\.com$
        • 匹配機制:

          (1) 首先是字符串精確匹配;
            (2) 左側*通配符;
            (3) 右側*通配符;
            (4) 正則表達式;
      4. tcp_nodelay on | off;
        在keepalived模式下的連接是否啟用TCP_NODELAY選項;

      5. sendfile on | off;
        是否啟用sendfile功能;
        不通過用戶空間,直接從內核空間向外轉發

      6. tcp_nopush on|off;
        在sendfile模式下,是否啟用TCP_CORK選項;
        是否等待應用層首部合并起來一并發送;

    • 定義路徑相關的配置:

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

      2. location [ = | ~ | ~* | ^~ ] uri { … }
        Sets configuration depending on a request URI.

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

          =:對URI做精確匹配;例如, http://www.magedu.com/, http://www.magedu.com/index.html
            location  =  / {
                ...
            }
          ~:對URI做正則表達式模式匹配,區分字符大小寫;
          ~*:對URI做正則表達式模式匹配,不區分字符大小寫;
          ^~:對URI的左半部分做匹配檢查,不區分字符大小寫;
          不帶符號:匹配起始于此uri的所有的url;
        • 匹配優先級:=, ^~, ~/~*,不帶符號;
      3. alias path;

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

        • 注意:location中使用root指令和alias指令的意義不同;
          (a) root,給定的路徑對應于location中的/uri/左側的/;
          (b) alias,給定的路徑對應于location中的/uri/右側的/;

      4. index file …;
        默認資源;http, server, location;

      5. error_page code … [=[response]] uri;
        Defines the URI that will be shown for the specified errors.

      6. try_files file … uri;

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

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

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

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

      4. send_timeout time;
        向客戶端發送響應報文的超時時長,此處,是指兩次寫操作之間的間隔時長;

      5. client_body_buffer_size size;
        用于接收客戶端請求報文的body部分的緩沖區大?。荒J為16k;超出此大小時,其將被暫存到磁盤上的由client_body_temp_path指令所定義的位置;

      6. client_body_temp_path path [level1 [level2 [level3]]];

        • 設定用于存儲客戶端請求報文的body部分的臨時存儲路徑及子目錄結構和數量;

        • 對URL進行哈希計算,http://host:port/path hash;生成16進制數字的目錄;
          client_body_temp_path /var/tmp/client_body 2 1 1
          1:表示用一位16進制數字表示一級子目錄;0-f
          2:表示用2位16進程數字表示二級子目錄:00-ff
          2:表示用2位16進程數字表示三級子目錄:00-ff

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

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

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

        limit_except GET {
            allow 192.168.1.0/24;
            deny  all;
        }
    • 文件操作優化的配置

      1. aio on | off | threads[=pool];
        是否啟用aio功能;

      2. directio size | off;
        在Linux主機啟用O_DIRECT標記,此處意味文件大于等于給定的大小時使用,例如directio 4m;

      3. open_file_cache off;
        open_file_cache max=N [inactive=time];

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

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

        • inactive=time:緩存項的非活動時長,在此處指定的時長內未被命中的或命中的次數少于open_file_cache_min_uses指令所指定的次數的緩存項即為非活動項;

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

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

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

  • ngx_http_access_module模塊:

    • 實現基于ip的訪問控制功能
      使用:http, server, location, limit_except
    1. allow address | CIDR | unix: | all;
    2. deny address | CIDR | unix: | all;
  • ngx_http_auth_basic_module模塊
    實現基于用戶的訪問控制,使用basic機制進行用戶認證;

    1. auth_basic string | off;
    2. 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所提供;

  • ngx_http_stub_status_module模塊
    用于輸出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:處于等待客戶端發出請求的空閑連接數;
    • stub_status;

    • 配置示例:

      location  /basic_status {
            stub_status;
        }
  • ngx_http_log_module模塊
    he ngx_http_log_module module writes request logs in the specified format.

    • log_format name string …;

      • string可以使用nginx核心模塊及其它模塊內嵌的變量;
        “$http_x_forwarded_for” 用來記錄真正的客戶端地址,正常情況下服務器記錄的是反向代理的IP地址
    • access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];

      • access_log off;
      • 訪問日志文件路徑,格式及相關的緩沖的配置;
        buffer=size
        flush=time
    • open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];

      • open_log_file_cache off;
        緩存各日志文件相關的元數據信息;緩存加速讀;

      • max:緩存的最大文件描述符數量;

      • min_uses:在inactive指定的時長內訪問大于等于此值方可被當作活動項;
      • inactive:非活動時長;
      • valid:驗正緩存中各緩存項是否為活動項的時間間隔;
  • ngx_http_gzip_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.

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

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

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

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

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

    • 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的值為此三者中任何一個,則啟用壓縮功能;
    • gzip_types mime-type …;
      壓縮過濾器,僅對此處設定的MIME類型的內容啟用壓縮功能;

    • 示例:

      gzip  on;
        gzip_comp_level 6;
        gzip_min_length 64;
        gzip_proxied any;
        gzip_types text/xml text/css  application/javascrip
  • ngx_http_ssl_module模塊:

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

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

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

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

    • ssl_session_cache off | none | [builtin[:size]] [shared:name:size];

      • builtin[:size]:使用OpenSSL內建的緩存,此緩存為每worker進程私有;

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

    • 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;
        }
  • ngx_http_rewrite_module模塊:

    • The ngx_http_rewrite_module module is used to change request URI using PCRE regular expressions, return redirects, and conditionally select configurations.

    • http://www.ilinux.io/bbs/ –> http://bbs.ilinux.io/

    • 將用戶請求的URI基于regex所描述的模式進行檢查,而后完成替換;

    • rewrite regex replacement [flag]

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

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

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

      • [flag]:

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

      return code [text];
      return code URL;
      return URL;
    • rewrite_log on | off;
      是否開啟重寫日志;

    • if (condition) { … }
      引入一個新的配置上下文 ;條件滿足時,執行配置塊中的配置指令;server, location;

      • condition:

        比較操作符:
          ==
          !=
          ~:模式匹配,區分字符大小寫;
          ~*:模式匹配,不區分字符大小寫;
          !~:模式不匹配,區分字符大小寫;
          !~*:模式不匹配,不區分字符大小寫;
        文件及目錄存在性判斷:
          -e, !-e
          -f, !-f
          -d, !-d
          -x, !-x
    • set $variable value;
      用戶自定義變量;

  • ngx_http_referer_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.

    • 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;
      }
  • ngx_http_proxy_module模塊:
    The ngx_http_proxy_module module allows passing requests to another server.

    • proxy_pass URL;
      Context:location, if in location, limit_except

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

        server {
          ...
          server_name HOSTNAME;
          location /uri/ {
              proxy http://hos[:port];
          }
          ...
        }
        
        http://HOSTNAME/uri --> http://host/uri
      • proxy_pass后面的路徑是一個uri時,其會將location的uri替換為proxy_pass的uri;

        server {
          ...
          server_name HOSTNAME;
          location /uri/ {
              proxy http://host/new_uri/;
          }
          ...
        }
        
        http://HOSTNAME/uri/ --> http://host/new_uri/
      • 如果location定義其uri時使用了正則表達式的模式,則proxy_pass之后必須不能使用uri; 用戶請求時傳遞的uri將直接附加代理到的服務的之后;

        server {
          ...
          server_name HOSTNAME;
          location ~|~* /uri/ {
              proxy http://host;
          }
          ...
        }
        
        http://HOSTNAME/uri/ --> http://host/uri/;
    • proxy_set_header field value;
      設定發往后端主機的請求報文的請求首部的值;Context: http, server, location

      proxy_set_header X-Real-IP  $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    • proxy_cache_path
      定義可用于proxy功能的緩存;Context: http

      proxy_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];

    • proxy_cache zone | off;
      指明要調用的緩存,或關閉緩存機制;Context: http, server, location

    • proxy_cache_key string;
      緩存中用于“鍵”的內容;

      默認值:proxy_cache_key $scheme$proxy_host$request_uri;

    • proxy_cache_valid [code …] time;
      定義對特定響應碼的響應內容的緩存時長;

      • 定義在http{…}中;

        proxy_cache_path /var/cache/nginx/proxy_cache levels=1:1:1 keys_zone=pxycache:20m max_size=1g;
      • 定義在需要調用緩存功能的配置段,例如server{…};

        proxy_cache pxycache;
        proxy_cache_key $request_uri;
        proxy_cache_valid 200 302 301 1h;
        proxy_cache_valid any 1m;
    • proxy_cache_use_stale

      proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off …;

      Determines in which cases a stale cached response can be used when an error occurs during communication with the proxied server.

    • proxy_cache_methods GET | HEAD | POST …;
      If the client request method is listed in this directive then the response will be cached. “GET” and “HEAD” methods are always added to the list, though it is recommended to specify them explicitly.

    • proxy_hide_header field;
      By default, nginx does not pass the header fields “Date”, “Server”, “X-Pad”, and “X-Accel-…” from the response of a proxied server to a client. The proxy_hide_header directive sets additional fields that will not be passed.

    • proxy_connect_timeout time;
      Defines a timeout for establishing a connection with a proxied server. It should be noted that this timeout cannot usually exceed 75 seconds.
      默認為60s;最長為75s;

    • proxy_read_timeout time;
      Defines a timeout for reading a response from the proxied server. The timeout is set only between two successive read operations, not for the transmission of the whole response.

    • proxy_send_timeout time;
      Sets a timeout for transmitting a request to the proxied server. he timeout is set only between two successive write operations, not for the transmission of the whole request. If the proxied server does not receive anything within this time, the connection is closed.

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

    向由代理服務器響應給客戶端的響應報文添加自定義首部,或修改指定首部的值;

    • add_header name value [always];
      添加自定義首部;

      add_header X-Via  $server_addr;
      add_header X-Accel $server_name;
    • expires [modified] time;
      expires epoch | max | off;

      用于定義Expire或Cache-Control首部的值;

  • ngx_http_fastcgi_module模塊:

    • 網站開發:
      前端開發:javascript
      后端開發:
      runtime:perl/php/java/python/ruby/go
      系統開發會涉及到(conmpile):c/c++/rus

    • fpm:fastcgi進程管理工具

    • The ngx_http_fastcgi_module module allows passing requests to a FastCGI server.

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

    • fastcgi_index name;
      fastcgi默認的主頁資源;

    • 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;
        }
    • 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
          磁盤上用于緩存數據的緩存空間上限
    • fastcgi_cache zone | off;
      調用指定的緩存空間來緩存數據;http, server, location

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

    • fastcgi_cache_methods GET | HEAD | POST …;
      為哪些請求方法使用緩存;

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

    • fastcgi_cache_valid [code …] time;
      不同的響應碼各自的緩存時長;

      • 示例:

        http {
          ...
          fastcgi_cache_path /var/cache/nginx/fastcgi_cache levels=1:2:1 keys_zone=fcgi:20m inactive=120s;
          ...
          server {
              ...
              location ~* \.php$ {
                  ...
                  fastcgi_cache fcgi;
                  fastcgi_cache_key $request_uri;
                  fastcgi_cache_valid 200 302 10m;
                  fastcgi_cache_valid 301 1h;
                  fastcgi_cache_valid any 1m;    
                  ...
              }
              ...
          }
          ...
        }
    • fastcgi_keep_conn 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.
  • ngx_http_upstream_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 { … }
      定義后端服務器組;引入一個新的上下文;只能用于http{}上下文中;

      默認的調度方法是wrr;

    2. server address [parameters];
      定義服務器地址和相關的參數;

      • 地址格式:
        IP[:PORT]
        HOSTNAME[:PORT]
        unix:/PATH/TO/SOME_SOCK_FILE

      • 參數:
        weight=number權重,默認為1;
        max_fails=number失敗嘗試的最大次數;
        fail_timeout=time設置服務器為不可用狀態的超時時長;
        backup把服務器標記為“備用”狀態;
        down手動標記其為不可用;

    3. least_conn;
      最少連接調度算法; 當server擁有不同的權重時為wlc;當所有后端主機的連接數相同時,則使用wrr進行調度;

    4. ip_hash;
      源地址hash算法;能夠將來自同一個源IP地址的請求始終發往同一個upstream server;

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

      consistent:參數,指定使用一致性hash算法;

      示例:

      hash $request_uri consistent
       hash $remote_addr
       hash $cookie_name
    6. keepalive connections;
      可使用長連接的連接數量;

  • ngx_stream_core_module

    The ngx_stream_core_module module is available since version 1.9.0. This module is not built by default, it should be enabled with the –with-stream configuration parameter.

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

      • 監聽的端口;
        默認為tcp協議端口;
        udp: 監聽udp協議的端口;
  • ngx_stream_proxy_module

    The ngx_stream_proxy_module module (1.9.0) allows proxying data streams over TCP, UDP (1.9.13), and UNIX-domain sockets.

    1. proxy_pass address;
      Sets the address of a proxied server. The address can be specified as a domain name or IP address, and a port or as a UNIX-domain socket path.

    2. proxy_timeout timeout;默認為10m;
      Sets the timeout between two successive read or write operations on client or proxied server connections. If no data is transmitted within this time, the connection is closed.

    3. proxy_connect_timeout time;
      Defines a timeout for establishing a connection with a proxied server.
      設置nginx與被代理的服務器嘗試建立連接的超時時長;默認為60s;

    • 示例:

      stream {
            upstream sshsrvs {
                server 192.168.10.130:22;
                server 192.168.10.131:22;
                hash $remote_addr consistent;
            }
      
            server {
                listen 172.16.100.6:22202;
                proxy_pass sshsrvs; 
                proxy_timeout 60s;
                proxy_connect_timeout 10s;
            }
        }

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

(0)
ss
上一篇 2017-06-25 23:25
下一篇 2017-06-25

相關推薦

  • Find命令以及解壓與壓縮文件的相關指令

    1,find   實時查找,通過遍歷指定路徑完成文件的查找 查找路徑:指定具體目標路徑,默認為當前目錄 查找條件:指定的查找標準,可以文件名,大小,類型,權限等標準進行,默認為找出指定路徑下的所有文件 處理動作:對符合條件的文件做操作,默認輸出至屏幕 find -maxdepth level  最大搜索目錄深度 -mindept…

    2017-08-12
  • linux系統上的特殊權限SUID,SGID,STICKY

    特殊權限:SUID SGID STICKY     linux的安全上下文:     1.進程以用戶的身份運行,進程是發起此用戶的代理,因此以此用戶的身份和權限完成所有的操作。     2.權限匹配模型:     1)判斷進程的屬主,是否以被訪問的文件屬主。如果是,則應用屬主權限…

    Linux干貨 2016-08-05
  • 第二周

    #第二周blog 作業 第二周blog 作業 1 目錄管理命令:mkdir、rmdir mkdir命令 mkdir – make directories      mkdir [OPTION]… DIRECTORY…   &nbsp…

    Linux干貨 2016-12-12
  • 計算機的組成及功能

    計算機的組成及功能 計算機由CPU、存儲器、輸入設備、輸出設備等部件組成。 CPU:為計算機的中央處理器,是計算機的核心部分,由運算器和控制器組成。 運算器:CPU中用于進行算術運算和邏輯運算的部件。 控制器:整個CPU的指揮中心,控制程序中指令讀取、解析并產生相應的操作控制信息保證各程序的有序執行。 存儲器:計算機中用來存儲數據、程序等信息的部件,并在需要…

    Linux干貨 2017-07-02
  • linux基礎知識:文件管理,bash特性

    本文簡要介紹了文件類的管理命令,包括mv、cp、mkdir等等。還介紹了一些萬用字符的用法。

    2017-12-12
  • 細說linux上的特殊權限位

    linux上的文件的權限 linux的哲學思想之一就是一切皆文件。這樣說來,每臺安裝了linux的主機上,就會有大量的文件。而另一方面,linux在安全方面有著極為出色的表現。眾所周知,linux是一個多用戶的系統,因此為一個文件加上合適的權限為顯得非常有必要了。linux上的基本權限我就不一一介紹了,請不熟悉的同學自行百度腦補。我們來說說linux上文件和…

    Linux干貨 2017-04-10
欧美性久久久久