Nginx及Nginx模塊——更加輕量級的HTTP server

Nginx

engine X = Nginx

    

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進程:處理并響應用戶請求

         緩存相關的進程:

                 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 {

        

         }    :和tcp/udp協議的反代有關;

http協議相關的配置結構

http {

        

         …:各server的公共配置

         server {

        

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

         server {

                

                 server_name

                 root

                 alias

                 location [OPERATOR] URL {

                        

                         if CONDITION {

                             

                         }

                 }

         }

}

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

         分類:

                 正常運行必備的配置

                 優化性能相關的配置

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

                 事件驅動相關的配置

        

nginx配置文件的詳細說明:http://nginx.org/en/docs/

正常運行必備的配置:

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;

指明包含進來的其它配置文件片斷;Context: main, http

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;默認是on

2、master_process on|off;

是否以master/worker模型運行nginx;默認為on

3、error_log file [level];

事件驅動相關的配置:

events {

    …

}    :以下配置都是配置在events中

1、worker_connections number;

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

    

worker_processes * worker_connections

2、use method;

指明并發連接請求的處理方法;默認使用epoll

3、accept_mutex on | off;

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

ngx_http_core_module模塊:

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;

Default: tcp_nodelay on;

Context: http, server, location

在keepalived模式下的連接是否啟用TCP_NODELAY選項;等待多個報文包到達一并返回

最好不要開啟此功能,否則用戶體驗會變差

5、sendfile on | off;

是否啟用sendfile功能;在內核中直接封裝報文返回客戶端

定義路徑相關的配置

1、root path;

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

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

location @name { … }

    

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

    

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

             location = / {

                 

             }

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

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

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

         不帶符號:匹配起始于此uri的所有的url;

        

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

        

         root /vhosts/www/htdocs/

             http://www.magedu.com/index.html –> /vhosts/www/htdocs/index.html

        

         server {

                 root  /vhosts/www/htdocs/

                

                 location /admin/ {

                      root /webapps/app1/data/

                 }

         }

3、alias path;

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

    

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

         (a) root,給定的路徑對應于location中的/uri/左側的/;即location后的路徑要追加在root給定路徑之后

    

         (b) alias,給定的路徑對應于location中的/uri/右側的/;即location后的路徑替換了alias路徑中的最后一個文件夾名字

4、index file …;

默認資源;http, server, location

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

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

    

errot_page 404 =200 /404.html :重定義了狀態響應碼

    

location = /404.html {

    root /usr/share/nginx/html;

}

6、try_files file … uri;

文件映射基于hash來實現

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

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部分的緩沖區大??;默認為16k;超出此大小時,其將被暫存到磁盤上的由client_body_temp_path指令所定義的位置

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

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

    

     16進制的數字;

    

     client_body_temp_path path  /var/tmp/client_body  1 2 2

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

1、limit_rate rate;

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

2、limit_except method … { … }

限制對指定的請求方法之外的其它方法的使用客戶端;Context: location

limit_except GET {

         allow 192.168.1.0/32;

         deny  all;

}

文件操作優化的配置

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

是否啟用aio功能

2、directio size | off;

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

例如directio 4m;當文件大于4m則啟動directio機制,從磁盤加載文件到內核中,直接從內核封裝報文

3、open_file_cache off;

open_file_cache max=N [inactive=time];

         nginx可以緩存以下三種信息:

                 (1) 文件的描述符、文件大小和最近一次的修改時間

                 (2) 打開的目錄結構

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

        

         通常定義在http中,多所有的server都生效

        

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

        

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

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的訪問控制功能;Context: 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:處于等待客戶端發出請求的空閑連接數

1、stub_status;

配置示例:

         location  /basic_status {

             stub_status;

         }

ngx_http_log_module模塊:

The ngx_http_log_module module writes request logs in the specified format.

1、log_format name string …;

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

    

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

    

log_format gm '$remote_addr $remote_user – [$time_local] '

              '"$request" $status $body_bytes_sent '

              '"$http_referer" "$http_user_agent"'

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

access_log off;

access_log  /var/log/nginx/access.log  gm;

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

         buffer=size

         flush=time

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

open_log_file_cache off;

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

        

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

         min_users:在inactive指定的時長內訪問大于等于此值方可被當作活動項

         inactive:非活動時長

         valid:驗正緩存中各緩存項是否為活動項的時間間隔

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.

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

1、rewrite regex replacement [flag]

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

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

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

    301:永久重定向;

[flag]:

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

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

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

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

rewrite ^/bbs/(.*)$ /alias/$1 redirect;

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;

用戶自定義變量

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.

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類型的內容啟用壓縮功能

ngx_http_fastcgi_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所指定路徑來定義;

一般寫在http段

        

         levels=levels:緩存目錄的層級數量,以及每一級的目錄數量;levels=ONE:TWO:THREE

                 leves=1:2:2

                         1級子目錄16個文件,2級子目錄256個文件,3級子目錄256個文件

                         把文件內容的hash碼做為cache中的文件名

                         把hash值的第1個匹配1級子目錄  把2-3位所在的字符匹配2級子目錄

                         但是nginx的hash比較時從最后一位開始比較的

        

         keys_zone=name:size

             k/v映射的內存空間的名稱及大小

         inactive=time

             非活動時長

         max_size=size

             磁盤上用于緩存數據的緩存空間上限

5、fastcgi_cache zone | off;

調用指定的緩存空間來緩存數據;http, server, location

zone的值要同fastcgi_cache_path 中keys_zone 中的name參數

6、fastcgi_cache_key string;

定義用作緩存項的key的字符串

7、fastcgi_cache_methods GET | HEAD | POST …;

為哪些請求方法使用緩存

默認的方法是GET、HEAD

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;

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

}

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;

}


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

(0)
megedugaomegedugao
上一篇 2016-10-25
下一篇 2016-10-25

相關推薦

  • ntp時間服務器搭建實例

    ntp時間服務器采用stratum分級架構來處理時間同步;舉例說明:你搭建了一臺ntp服務器,然后同步的server為stratum-1,你的ntp則為stratum-2,你的下級ntp則為tratum-3。依此類推,最多為15層。 1.ntp server安裝: [root@localhost ~]# yum -y …

    Linux干貨 2015-11-10
  • “拆”解RAID工作原理

    一、什么是RAID RAID:Redundant Arrays of Inexpensive(Independent)Disks,廉價(獨立)的冗余磁盤陣列。1988年由加利福尼亞大學伯克利分校提出。使用多個相對便宜的磁盤通過某種方式組合成一個“陣列”,來提供更好的性能、冗余,或兩者同時提供。 性能提高:     &n…

    Linux干貨 2016-11-22
  • 文本處理三劍客之sed及vi編輯使用

    作用:       sed是Linux系統文本處理工具中的三劍客之一,它是一種流編輯器,以行為單位,能夠使用正則表達式;跟其他文本處理工具模式相同,不對原文件直接操作,而是先借用一個臨 時的數據緩沖區存放文文本數據,同時還有一個自己獨特的空間"pattern space",我們稱之為sed的模式空間,它的處理…

    Linux干貨 2016-08-11
  • 邏輯卷實例

    1、創建一個至少有兩個PV組成的大小為20G的名為testvg的VG;要求PE大小為16MB, 而后在卷組中創建大小為5G的邏輯卷testlv;掛載至/users目錄 2、新建用戶archlinux,要求其家目錄為/users/archlinux,而后su切換至archlinux用戶,復制/etc/pam.d目錄至自己的家目錄 3、擴展testlv至7G,要…

    Linux干貨 2016-09-01
  • bash腳本進階

    case  變量引用  in PAT1)分支1 ;; PAT2)  分支2 ;; … *) 分支n ;; esac case支持glob風格的通配符:   *:任意長度任意字符: ?:任意單個字符: [ ]:指定范圍內的任意單個字符: a|b:a或b function:函數   &nbs…

    Linux干貨 2017-05-21
  • 從“黑掉Github”學Web安全開發

    Egor Homakov(Twitter: @homakov 個人網站: EgorHomakov.com)是一個Web安全的布道士,他這兩天把github給黑了,并給github報了5個安全方面的bug,他在他的這篇blog——《How I hacked Github again》(墻)說明了這5個安全bug以及他把github…

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