Nginx介紹及使用

   Nginx(engine x)是一個高性能的HTTP和反向代理服務器, 也是一個IMAP/POP3/SMTP服務器. Nginx是由IgorSysoev為俄羅斯訪問量第二的Rambler.ru站點開發的, 第一個公開版本在2004年發布. 因為它的穩定性, 豐富的功能集, 示例配置文件和低系統資源的消耗而聞名. Nginx是一款輕量級的Web服務器/反向代理服務器及電子郵件代理服務器, 并在一個BSD-like協議下發行. 其特點是占用內存少, 并發能力強.

Nginx的程序架構:

    master/worker

        一個master進程: 負責加載配置文件、管理worker進程、平滑升級

        一個或多個worker進程: 處理并響應用戶請求

        緩存相關的進程:

            cache loader:載入緩存對象

            cache manager:管理緩存對象

    特性:異步、事件驅動和非阻塞

        并發請求處理:通過kevent/epoll/select

        文件IO:高級IO sendfile,異步,mmap

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

        模塊分類:

            核心模塊:core module

            標準模塊:

               Standard HTTP modules

               Optional HTTP modules

              Mail modules

              Stream modules

              3rd party modules

nginx的功用:

     靜態的web資源服務器;

     結合FastCGI/uwSGI/SCGI等協議反代動態資源請求;

     http/https協議的反向代理;

     imap4/pop3協議的反抽代理;

     tcp/udp協議的反代;

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
       	alias
       	location [OPERATOR] URL {
           	...
           	if CONDITION {
           	...
       	    	}
       	}
    }
}

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

     分類:

     正常運行必備的配置

     優化性能相關的配置

     用于調試及定位問題相關的配置

     事件驅動相關的配置

    正常 運行必備的配置:

1、user

Syntax: user user [group];

Default: user nobody nobody;

Context: main

2、pid /PATH/TO/PID_FILE;

指定存儲nginx主進程進程號碼的文件路徑;

3、include file | mask;

指明包含進來的其它配置文件片斷;

4、load_module file;

指明要裝載的動態模塊;

性能優化相關的配置:

1、worker_processes number | auto;

worker進程的數量;通常應該為當前主機的cpu的物理核心數;

2、worker_cpu_affinity cpumask …;

worker_cpu_affinity auto [cpumask];

CPU MASK:

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;

Context: events

每個worker進程所能夠打開的最大并發連接數數量, 默認512;

worker_processes * worker_connections

2、use method;

Context: events

指明并發連接請求的處理方法, 一般不用特別指出;

use epoll;

3、accept_mutex on | off;

Context: events

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

一. 與套接字相關的配置

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) 正則表達式;

4. tcp_nodelay on|off ;

在keeplived模式下的連接是否啟用TCP_NODELAY選項(是否關閉延遲發送)

5. sendfile on|off;  – 是否使用sendfile功能; 

默認關閉

context : http, server, location, if in location

示例 :

location /video/ {
    sendfile on;
    tcp_nopush on;
    aio on;
}

二. 路徑相關的配置 :

1. root – 定義web站點的根路徑映射, 用于 指明用戶請求的url所對應的本地文件系統上的文檔所在目錄路徑;

語法 : root path;

Context : http, server, location, if in location.

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

Syntax:

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

location @name { … }

Context : server, location

=  : 對URI做精確匹配;

~  : 對URI做正則表達式模式匹配, 區分字符大小寫;

~* : 對URI做正則表達式模式匹配, 不區分字符大小寫;

^~ : 對URI的左半部分做匹配檢查, 不區分字符大小寫;

不帶符號 : 匹配起始于此uri的所有的uri, 一般為uri提供默認配置;

匹配優先級 : '=' > '^~' > '~/~*' > '不帶符號'

3. alias 

定義路徑別名, 文檔映射的另一種機制;

Syntax : alias path;

Context : location

示例 1 :

location /i/ {
    alias /data/w3/images/;
}
如果訪問"/i/top.gif", 文件 "/data/w3/images/top.gif"會被發送.

示例 2 :

location /i/ {
    root /data/w3/;
}
如果訪問"/i/top.gif", 文件"/data/w3/i/top.gif"會被發送

注意 : location中使用root指令和alias指令的意義不同;

     (a) root, 給定的路徑對應于location中的/uri/左側的 '/';

     (b) alias, 給定的路徑對應于location中的/uri/右側的 '/';

4. index file; – 定義默認主頁資源

context : http, server, location

5. error_page code…[=[response]] uri;

context : http, server, location, if in location

自定義錯誤頁面信息; 

6.  try_files file … uri;

try_files file … =code;

Default:

Context: server, location

檢查指定順序中文件的存在,并使用第一個找到的文件進行請求處理; 在當前上下文中執行處理。

location / {
    try_files $uri $uri/ @drupal;
}

location ~ \.php$ {
   try_files $uri @drupal;

   fastcgi_pass ...;

   fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
   fastcgi_param SCRIPT_NAME     $fastcgi_script_name;
   fastcgi_param QUERY_STRING    $args;

   ... other fastcgi_param's
}

location @drupal {
   fastcgi_pass ...;

   fastcgi_param SCRIPT_FILENAME /path/to/index.php;
   fastcgi_param SCRIPT_NAME     /index.php;
   fastcgi_param QUERY_STRING    q=$uri&$args;

   ... other fastcgi_param's
}

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

1. keepalive_timeout timeout;

Context : http, server, location

保持連接的超時時長, 0表示禁止長連接, 默認為75秒

2. keepalive_requests number;

Context : http, server, location

默認100; 在一次長連接上所允許請求的資源的最大數量;

3. keepalive_disable none|browser(瀏覽器);

Context : http, server, location

設定對哪種瀏覽器禁用保持連接功能;

4. send_timeout time;

Context : http, server, location

設定向客戶端發送響應報文的超時時長, 此處指兩次寫操作之間的間隔時長;

默認60秒;

5. client_body_buffer_size size;

Context : http, server, location

設置用于接收客戶body請求報文的緩沖區大小; 

默認為16K; 超出此大小時, 其將被暫存到磁盤上的由client_body_temp_path指令所定義的位置;

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

Context : http, server, location

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

level的數值 表示16進制數字的 位數, 最大為2, 每一級有 0~ 16 ~ 16×16 種變化.

示例:client_body_temp_path /var/tmp/client_body 1 2 2

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

1. limit_rate rate; 

限制對客戶端的響應傳輸速度, 單位是bytes/second, 0表示無限制;

Context : http, server, location, if in location

示例:

server {
    if ($slow) {
        set $limit_rate 4k;
    }
}

2. limit_except method … {…};

限制對指定的請求方法之外的其他方法的使用客戶端;

示例:

limit_except GET {
    allow 192.168.1.0/32;
    deny all;
}

五. 文件操作優化的配置:

1. aio on|off|threads[=pool]; 

Context: http, server, location

是否啟用aio功能(異步IO);

示例:

location /video/ {
    aio on;
    output_buffers 1 64k;
}

示例2:

location /video/ {
    sendfile	on;
    aio	        on;
    directio    8m;
}

2. directio size | off;

Context: http, server, location

在linux主機上啟用O_DIRECT標記, 此處意味文件大于等于給定的大小時使用.

3. open_file_cache off;

open_file_cache max=N [inactive=time];

  默認關閉

  Context : http, server, location

Configures a cache that can be store, 配置一個可存儲的高速緩存;

nginx可以緩存以下三種信息

     (1) 文件描述符, 文件大小, 和最近一次的修改事件;

     (2) 打開的目錄結構;

     (3) 沒有找到的或者沒有權限訪問的文件的相關信息.

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

LRU : least recently used

inactive=time : 緩存項的非活動時長, 在此處指定的時長;

示例: 

open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_users 2;
open_file_cache_errors on;

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的訪問控制功能;

示例:

location {
    deny 192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny all;
}

1. allow address | CIDR | unix: | all;

Context: http, server, location, limit_except

2. deny address | CIDR | unix: | all;

Default:

Context: http, server, location, limit_except

七. ngx_http_auth_basic_module模塊

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

示例:

location {
    auth_basic "closed site";
    auth_basic_user_file  conf/htpasswd;
}

1. auth_basic string | off; 

是否啟用登陸驗證.

Context:  http, server, location, limit_except

2. auth_basic_user_file path;

Context:  http, server, location, limit_except

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

八. ngx_http_stub_status_module模塊  – 用于輸出nginx的基本信息

1. stub_status

示例:

location /basic_status {
    stub_status;
}

輸出結果如下:

Active connections: 291 

server  accepts   handled   requests

       16630948  16630948  31070465 

Reading: 6  Writing: 179  Waiting: 106 

Active connections : 活動狀態的客戶端連接數;

           accepts : 已經接受的客戶端請求的總數;

           handled : 已經處理完成的客戶端請求的總數;

          requests : 客戶端發來的總的請求數;

           Reading : 處于讀取客戶端請求報文首部的連接的連接數;

           Writing : 處于向客戶端發送響應報文過程中的鏈接數;

           Waiting : 處于等待客戶端發出請求的空閑連接數;

九. ngx_http_log_module模塊

用來管理訪問日志

1.  log_format name string…;

Context : http

string可以使用nginx核心模塊及其他模塊內嵌的變量;

2.  access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];

access_log off;

訪問日志文件路徑, 格式及相關的緩沖配置

buffer=size (臨時存儲的大小)

flush=time(多長時間寫一次磁盤)

3.  open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];

open_log_file_cache off;

緩存各日志文件相關的元數據信息;

max=N – 最大文件文件描述符數量;

inactive – 非活動時長;

min_user – 在inactive指定的時長內, 訪問大于等于此值方可被當作活動項;

valid – 驗證緩存中各緩存項是否為活動項的時間間隔;

十. ngx_http_rewrite_module

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

1. rewrite regex replacement[flag]

Context : server, location, if

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

注意:

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

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

301 : 永久重定向;

[flag]

    last : 默認行為; 重寫完成后停止對當前URI在當前location中后續的其他重寫操作, 而后對新的URI啟動新一輪重寫檢查; 提前重啟新一輪循環;

    break : 重寫完成后停止對當前URI在當前location中后續的其他重寫操作, 而后直接跳轉至重寫規則配置塊之后的其他配置; 結束循環;

    redirect : 重寫完成后以臨時重定向方式直接返回重寫后生成的新URI給客戶端, 由客戶端重新發起請求; 不能以http://和https://開頭;

    permanent : 重寫完成后以永久重定向方式直接返回重寫后生成的新URI給客戶端, 由客戶端重新發起請求; 

示例 :

server {
    ...
    rewrite ^(/download/.*)/media/(.*)\..*$  $1/mp3/$2.mp3 last;
    rewrite ^(/download/.*)/audio/(.*)\..*$  $1/mp3/$2.ra last;
    return 403;
}

2. Syntax: return code [text];

return code URL;

return URL;

Context: server, location, if

Stops processing and returns the specified code to a client; – 停止處理并將指定的代碼返回給客戶端;

3. rewrite_log on | off;

是否 開啟重寫日志;

4. if(condition) {…}

引入一個新的配置上下文; 條件滿足是, 執行配置塊中的配置命令;

Context : server, location;

condition:

比較操作符

==

!=

  ~ : 模式匹配, 區分字符大小寫

 ~* : 模式匹配,不區分字符大小寫

 !~ : 模式不匹配, 區分字符大小寫

!~* : 模式不匹配, 不區分字符大小寫

文件及目錄存在性判斷:

-e, !-e

-f, !-f

-d, !-d

-x, !-x

示例:

if ($http_user_agent ~ MSIE) {
    rewrite ^(.*)$ /msie/$1 break;
}
if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
    set $id $1;
}
if ($request_method = POST) {
    return 405;
}
if ($slow) {
    limit_rate 10k;
}
if ($invalid_referer) {
    return 403;
}

5. set $variable value;

Sets a value for the specified variable. 設置指定變量的值

十一. ngx_http_gzip_module模塊 

在給客戶端響應時, 這個模塊將一些需要過濾的文件信息壓縮傳送, 以提高速度.

1. gzip on | off;

Context : http, server, location, if in location

是否開啟gzipping 響應

2. gzip_comp_level level;

設置gzipping responses的壓縮等級, 1~9, 數字越高壓縮比越大, 占用資源越多;

3. gzip_disable regex…;

4. gzip_min_length length;

啟用壓縮功能的響應報文的大小閾值; 默認20

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 …;

Context : http, server, location

壓縮過濾器, 僅對此處設定的MIME類型的內容啟用壓縮功能;

示例 :

http {
    ...
    gzip on;
    gzip_comp_level 6;
    #gzip_disable .*MSIE.*;
    gzip_types (此處查看mime.types, 根據需要選擇);
    gzip_min_length 1K;
}

十二. ngx_http_fastcgi_module模塊

1. fastcgi_pass address;

Context : location, if in location

address為fsctcgi server的地址; 

2. fastcgi_index name;

Context : http, server, location

fastcgi默認的主頁資源

3. fastcgi_param parameter value [if_not_empty];

配置示例 1:

前提: 配置好php-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_param;
}

配置示例 2:

location ~* ^/(pm_status|ping)$ {
    include fastcgi_param;
    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=1:2:2, 三級緩存, 最大為2 , 是十六進制數字的位數

keys_zone=name:size     k/v映射的內存空間的名稱及大小

inactive=time : 非活動時長;

max_size=size: 磁盤上用于緩存數據的緩存空間上限;

5. fastcgi_cache zone|off;

調用指定的緩存空間來緩存數據

Context : http, server, location

6. fastcgi_cache_key string

定義用于緩存項的key的字符串;

7. fastcgi_cache_method GET | HEAD | POST …;

為哪些請求方法使用緩存; 

8. fastcgi_cache_min_uses number;

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

9. 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;
            ...
        }
        ...
    }
    ...
}

10. fastcgi_keep_conn on | off;

是否啟用fastcgi的保持連接功能

十三. ngx_http_ssl_module

1. ssl on | off;

Context : http, server

是否開始ssl模塊, 默認關閉;

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 | [buildin[: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;
}

十四. 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. 

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;
}

十五. ngx_http_proxy_module模塊

1、proxy_pass URL;

Context: location, if in location, limit_except

注意:

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

server {
    ...
    server_name HOSTNAME;
    location /uri/ {
        proxy http://host[:port];
    }
    ...
}

#http://HOSTNAME/uri --> http://host/uri

(2) 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/

(3) 如果location定義其uri時使用了正則表達式的模式,則proxy_pass之后必須不能使用uri; 用戶請求時傳遞的uri將直接附加代理到的服務的之后;

server {
    ...
    server_name HOSTNAME;
    location ~|~* /uri/ {
        proxy http://host;
    }
    ...
}
#http://HOSTNAME/uri/ --> http://host/uri/;

2、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;

3、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];

4、proxy_cache zone | off;

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

5、 proxy_cache_key string;

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

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

6、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;

7、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.

8、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. 

9、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.

10、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;

十六. buffer相關的配置

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.

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

1、add_header name value [always];

添加自定義首部;

add_header X-Via  $server_addr;

add_header X-Accel $server_name;

2、expires [modified] time;

expires epoch | max | off;

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

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.

十七. 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 { … }

定義后端服務器組,會引入一個新的上下文;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

十八. ngx_stream_core_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]];

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

(0)
black_fishblack_fish
上一篇 2016-11-11
下一篇 2016-11-11

相關推薦

  • DHCP使用幫助

    bootp 想要通過tcp/ip模型進行網絡通信需要有一個ip地址,IP地址是屬于操作系統的,所以沒有操作系統就沒有ip 為了解決這種問題,有一種網卡可以不需要操作系統就能獲取到ip bootp:只有第一次是動態獲得,以后ip地址就是和mac地址綁定的,不能分配給其他主機 DHCP:DHCP是bootp的改進版,主要引入了租約的定義 DHCP也可以根據mac…

    Linux干貨 2016-11-11
  • Python修飾器的函數式編程

    Python的修飾器的英文名叫Decorator,當你看到這個英文名的時候,你可能會把其跟Design Pattern里的Decorator搞混了,其實這是完全不同的兩個東西。雖然好像,他們要干的事都很相似——都是想要對一個已有的模塊做一些“修飾工作”,所謂修飾工作就是想給現有的模塊加上一些小裝飾(一些小功能,這些小功能可能好多模塊都會用到),但又不讓這個小…

    Linux干貨 2016-08-15
  • 磁盤管理

    磁盤管理     設備文件         I/O Ports: I/O設備地址         一切皆文件:     …

    Linux干貨 2016-09-01
  • MySQL基礎知識

    1、SQL:結構化查詢語言(Structured Query Language): DDL:Data?Definition?Language(數據定義語言):?其語句包括動詞CREATE和DROP。在數據庫中創建新表或刪除表(CREAT TABLE?或?DROP TABLE);為表加入索引等。DDL包括許多與人數據庫目錄中獲得數據有關的保留字。它也是動作查詢…

    2017-11-20
  • bash

    1.  bash的工作特性之命令執行狀態返回值和命令行展開所涉及的內容及其示例演示           狀態返回值:            &nbsp…

    Linux干貨 2016-11-06
  • 計算機基礎

    計算機組成 計算機發展史 采用電子管的第一代計算機(1946~1959年) 第一代計算機的內部元件使用的是電子管。第一代計算機主要用于科學研究和工程計算。 采用晶體管的第二代計算機(1960~1964年) 第二代計算機的內部元件使用的是晶體管,晶體管比電子管小得多,處理更迅速、更可靠。第二代計算機主要用于商業、大學教學和政府機關。 采用集成電路的第三代計算機…

    Linux干貨 2017-12-03
欧美性久久久久