Nginx — 配置文件詳細解讀(一)

Nginx — 配置文件詳細解讀(一)


Nginx是一款免費、開源、性能強大且非常流行的服務器,主要有三個功能:Web Server , Reverse Proxy Server , IMAP or POP3 Proxy Server 。Nginx是爲了解決互聯網業內著名的 “C10K” 問題而生,且因其具有豐富的特性、極其強大的性能、配置簡單、工作穩定及資源佔用低等特點而聞名於世。

Nginx的主要功能有:作爲Web服務器可與httpd服務一樣提供靜態的Web資源,結合FastCGI/uwSGI/SCGI等協議反代動態資源請求,http/https協議的反向代理,imap4/pop3協議的反向代理,tcp/udp協議的請求轉發(四層轉發)。

Nginx在功能豐富的同時,其配置文件種類非常多。但相對於httpd的配置文件來說,Nginx配置文件邏輯嚴謹,條理清晰,配置方法相對簡單。

  • 【注】本文全部示例以CentOS7.3作爲運行環境,使用Nginx版本爲EPEL源的Nginx-1.10.2。

Nginx配置詳解

配置文件的組成部分

  • 主配置文件:/etc/nginx/nginx.conf
  • 兩個配置段文件目錄

    include conf.d/*.conf

    include default.d/*.conf

配置指令格式及注意要點

directive value [value2 ...];

* ==編寫配置文件注意要點==*
1. 所有指令必須以分號結尾;
2. Nginx配置文件支持使用配置變量
內建變量:由Nginx模塊引入,可直接引用

自定義變量:使用set指令定義的變量;
3. 指令有使用位置要求,只有在適用的上下文中才能使用;
4. 某些指令(如root、alias)可以在不同的多個上下文中同時出現時,優先級高的生效,優先級低的不生效,注意指令執行或匹配的優先級;
5. 一個配置文件一般僅存在一個http配置段,一個http配置段可包含多個server虛擬主機配置段,一個server配置段內可存在多個location配置段;
6. 本文采用和Nginx官方文檔類似的格式對配置指令進行解讀,格式如下:
- Syntax :語法|句法,使用方法
- Default:默認value,在沒有顯式指定時該指令的默認值
- Context:上下文,即本指令可以在哪個配置段中使用,可能爲多個
- Example:示例,對本指令如何的簡單示例
- Notes :注意|註釋 ,注意要點或使用方法補充
- #註釋內容 :代表非正文註釋

配置文件結構

#主配置段,定義全局配置
main block { 
    #事件驅動相關配置段
    events { 
        ...
    }
    #Web服務及Reverse Proxy相關服務配置段
    http {
        ...
        #虛擬主機配置段
        server {
            ...
            #URI特性定義配置段
            location /URI {
                ...
            }
        }
    }
    #郵件服務配置段
    mail {
        ...
    }
    #stream模塊相關配置段(四層轉發)
    stream {
        ...
    }
}

主配置文件詳解

因爲Nginx豐富的特性,使得配置文件中指令繁多且組合方式不勝枚舉,爲了方便梳理整體結構,對主配置文件中的各類配置指令進行分類。

主配置文件位置:/etc/nginx/nginx.conf

  • 第一類:Nginx正常運行必備的基本配置
  • 第二類:優化Nginx工作性能的配置
  • 第三類:events相關配置
  • 第四類:用於Nginx調試和問題定位的相關配置

第一類:Nginx正常運行必備的基本配置

1. user :指定worker進程的用戶和組
- Syntax :==user USER_NAME [GROUP_NAME];==
- Default :user nobody nobody;
- Context :main
- Example :user nginx nginx;

2. pid :指定nginx進程的pid文件
- Syntax :pid /PATH/TO/pid_file;
- Default :pid nginx.pid;
- Context :main
- Example :pid /var/run/nginx/nginx.pid;

3. worker_rlimit_nofile :設置全部worker進程一共能打開的最大文件句柄數
- Syntax :==worker_rlimit_nofile #;==
- Default:——
- Context:main
- Example:worker_rlimit_nofile 10240;
- Notes :本指令設置的數值大小即單個worker進程所能響應的併發連接數的上限

第二類:優化Nginx性能的相關配置

1. worker_processes :設置worker進程的個數
- Syntax :==worker_processes #|auto;==
- Default :worker_processed 1;
- Context :main
- Example :worker_processes 3;
- Notes :auto代表程序自動檢測硬件後選擇,此數值應該小於等於服務器CPU物理核芯的顆數,否則會起到反面效果。

2. worker_cpu_affinity :配置cpu綁定
- Syntax1 :worker_cpu_affinity CPU_MASK …;
- Syntax2 :==worker_cpu_affinity auto;==
- Default :——
- Context :main
- Example1:worker_cpu_affinity 00000001 00000010 00000100 #綁定第1、2、3顆cpu
- Example2:worker_cpu_affinity auto; #自動選擇綁定
- Notes :建議使用auto ,此配置可提升cpu緩存的命中率,提高性能

  1. time_resolution :計算器解析度
    • Syntax :time_resolution INTERVAL;
    • Default :——
    • Context :main
    • Example :time_resolution 100ms;
    • Notes :降低此值可減少gettimeofday()系統調用的次數,提高性能

4. worker_priority :指明worker進程的nice值
- Syntax :==worker_priority #;==
- Default :worker_priority 0;
- Context :main
- Example :worker_priority -5;
- Notes :數值範圍:-20~20,nice值越小,優先被調度的等級越高

第三類 :events相關配置

  1. accept_mutex :主控進程master調度用戶的請求至各worker進程時使用的負載均衡鎖
    • Syntax :accept_mutex {on|off};
    • Default :off
    • Context :events
    • Example :accept_mutex off;

- Notes1 :on 表示能讓多個worker輪流的、序列化的響應新的請求,off表示多個worker進程一同接收master的調度,哪個worker接收到,其他的worker則不接收。

* Notes2 :推薦使用off選項,on選項保證了每個worker從master調度後接收到的請求數幾乎相同,即保證了各個worker的起點平衡;off選項保證了接收調度的請求速度快的worker能優先接收,因每個用戶請求的處理時間不同,會導致某些worker會比較空閒,有些worker會比較繁忙,一般來說,空閒的worker會比繁忙的worker接收的速度快,off選項保證了各個worker進程的終點平衡。*

  1. lock_file :設置鎖文件的路徑

    • Syntax :lock_file FILE;
    • Default :lock_file logs/nginx.lock;
    • Context :main
    • Example :lock_file logs/nginx.lock;
    • Notes :指accept_mutex用到的鎖文件路徑
  2. use :指明使用的事件模型

    • Syntax :use METHOD; #METHOD爲{epoll|rtsig|select|poll}
    • Default :——
    • Context :events
    • Example :use epoll;
    • Notes :此項設置建議讓nginx自動選擇

4. worker_connections :配置單個worker進程能處理的最大併發連接數量
- Syntax :==worker_connections #;==
- Default :worker_connections 512;
- Context :events

- Example :worker_connections 10240;

Notes1 :此數值不能超過 “worker_rlimit_nofile” 指令設置的值

Notes2 :nginx能響應的所有併發連接數爲:單個worker進程能響應的數量 * worker進程數量
- Notes3 :該項設置需根據服務器的實際性能設置,不可設置過大(會起到反面效果)或過小(資源過剩導致浪費)。

第四類:用於Nginx調試和問題定位的相關配置

  1. daemon :Nginx是否以守護進程方式運行的開關選項

    • Syntax :daemon {on|off};
    • Default :on
    • Context :main
    • Example :daemon on;
    • Notes :調試時應該設置爲off,其他情況下應該設置爲on
  2. master_process :Nginx是否以master/worker模型來運行的開關選項

    • Syntax :master_process {on|off};
    • Default :on
    • Context :main
    • Example :master_process on;
    • Notes :調試時可以設置爲off
  3. error_log :錯誤日誌存儲位置和記錄的啓用級別

    • Syntax :error_log FILE [level];
    • Default :error_log logs/error.log error;
    • Context :main, http, mail, stream, server, location
    • Example :error_log /var/logs/nginx/error.log error;
    • Notes :若要使用debug級別,需要在編譯時增加 ” –with-debug ” 選項

Nginx的Web Server和Reverse Proxy Server配置詳解

Nginx配置也採用了流行的類似容器的片段式配置分段方法,各虛擬機的配置可保存在一個單獨的以 “.conf” 爲後綴的文件,通過主配置文件中的 “include” 指令加以調用,使配置文件可以更加靈活的啓用或停用。Nginx默認的配置段目錄有兩個:”/etc/nginx/conf.d/” 和 “/etc/nginx/default.d” 。

Nginx以強大的Web服務和Reverse Proxy服務的高併發響應能力聞名,有了以上配置的基礎,我們來見識下Nginx最出名的服務的配置方法。本部分以模塊的不同對配置指令進行分類

配置按模塊分類

1. http模塊相關配置

  • ngx_http_core_module模塊

    1. 訪問控制模塊
  • ngx_http_access_module模塊
  • ngx_http_auth_basic_module模塊

    1. 狀態頁、日誌、壓縮模塊
  • ngx_http_stub_status_module模塊
  • ngx_http_log_module模塊
  • ngx_http_gzip_module

4. https模塊

  • ngx_http_ssl_module模塊

    1. URL重定向模塊
  • ngx_http_rewrite_module模塊

    1. 鏈接引用模塊
  • ngx_http_referer_module模塊

    1. 響應報文首部修改模塊
  • ngx_http_headers_module模塊

8. 反向代理模塊

  • ngx_http_proxy_module模塊
  • ngx_http_fastcgi_module模塊

http模塊相關配置

與套接字相關的配置

  1. server :虛擬主機配置
    • Syntax :==server {…}==
    • Default :——
    • Context :http
    • Example
server {
    listen address[:PORT]|PORT;
    server_name SERVER_NAME;
    root /PATH/TO/DOCUMENT_ROOT;                            
}
  • Notes :Nginx中的虛擬主機與httpd類似,也可以基於IP、PORT、SERVER_NAME三種方式建立不同的虛擬主機。

    1. listen :監聽端口
  • Syntax :==listen ADDRESS:PROT [default_server] [ssl] [http2 | spdy] [backlog=number] [rcvbuf=size] [sndbuf=size];==
  • Default :listen {(:80)|(:8080)};
  • Context :server
  • Example1:listen 80 default_server;
  • Example2:listen *:8080;
  • Example3:listen 127.0.0.1:443 ssl;
  • Example4:listen localhost:8000;
  • Notes :default_server:設定爲默認虛擬主機;
    ssl:限制僅能夠通過ssl連接提供服務;
    backlog=number:後援隊列長度;
    rcvbuf=size:接收緩衝區大小;
    sndbuf=size:發送緩衝區大小;

    1. server_name :設置虛擬主機名稱
  • Syntax :==server_nmae NAME;==
  • Default :server_nmae “”;
  • Context :server
  • Example :server_name www.achudk.com;
  • Notes1 :支持通配任意長度的任意字符;server_name .magedu.com www.magedu.*;支持~起始的字符做正則表達式模式匹配;server_name ~^www\d+\.magedu\.com$
  • Notes2 :匹配機制:
    (1) 首先是字符串精確匹配;
    (2) 左側*通配符;
    (3) 右側*通配符;
    (4) 正則表達式.

    1. tcp_nodelay :在keepalived模式下的連接是否啓用TCP_NODELAY選項
  • Syntax :tcp_nodelay on | off;
  • Default :tcp_nodelay off;
  • Context :http, server, location
  • Example :tcp_nodelay on;
  • Notes :建議設置爲on,設置爲off時雖然會節省服務器端資源,但會降低用戶體驗。

    1. tcp_nopush :在sendfile模式下,是否啓用TCP_CORK選項
  • Syntax :tcp_nopush on|off;
  • Default :tcp_nopush off;
  • Context :http, server, location
  • Example :tcp_nopush on;
  • Notes :建議設置爲on,該選項生效的前提是sendfile功能已啓用。

    1. sendfile :是否啓用sendfile功能
  • Syntax :sendfile on | off;
  • Default :sendfile off;
  • Context :http, server, location, if in location
  • Example :sendfile on;
  • Notes :建議設置爲on 。

定義URI映射路徑相關的配置

  1. root :設置web服務URL資源映射的本地文件系統的資源所在的目錄

    • Syntax :==root /PATH/OF/ROOT;==
    • Default :root html;
    • Context :http, server, location, if in location
    • Example :root /web/nginx;
    • Notes :注意root與alias的區別。
  2. ==location :設置請求的URI的屬性和功能特性==

    • Syntax :location [ = | ~ | ~* | ^~ ] uri { … }
    • Syntax :location @name { … }
    • Default :——
    • Context :server,location
    • Example :這裏引用官網上的一個示例:
    location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}
  • Notes1 :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.

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

  • Notes3 :

匹配符號:

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

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

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

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

匹配優先級:

從高到低依次爲:=, ^~, ~/~*,不帶符號;

  1. alias :定義路徑別名
    • Syntax :alias /PATH/TO/ALIAS_DIR;
    • Default :——
    • Context :location
    • Example1:如果請求host/abc/1.jpg,則用/data/w3/images/1.jpg響應請求。
location /abc/ {
    alias /data/w3/images/;
}
  • Example2:如果請求host/abc/1.jpg,則用/data/w3/images/abc/1.jpg響應請求。
location /abc/ {
    root /data/w3/images/;
}
  • Notes1 :==root和alias二者映射的路徑的異同點==

相同點:都是從給定的路徑(/web/html/或/vhost/picture)的右側開始匹配;

不同點:root從給出的路徑(/web/html/)的右側匹配訪問時輸入的的URL(/images)路徑的左側,alias從給出的路徑(/vhost/picture)的右側匹配訪問時輸入的URL(/images)路徑的右側。

  • Notes2 :注意URI和映射的路徑的格式要對應:

如果給定的URL末端有” / ” ,則下面的root或alias的路徑末端也必須有” / “,如果沒有” / ” 則都應該沒有。

  1. index :定義默認主頁面

    • Syntax :index index.{html|php|htm|…};
    • Default :——
    • Context :server
    • Example :index index.html index.php;
  2. error_page 指定錯誤頁面

    • Syntax :error_page code […] [=code] URI;
    • Default :——
    • Context :http, server, location, if in location
    • Example :
error_page 404             /404.html;
error_page 500 502 503 504 /50x.html;
  • Notes :[=code] :以指定的響應碼進行響應,而不是默認的原來的響應,默認表示以新資源的響應碼爲其響應碼.

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

  1. keepalive_timeout :設定保持連接的超時時長

    • Syntax :keepalive_timeout TIMEOUT [head_timeout];
    • Default :75s
    • Context :http, server, location
    • Example :keepalive_timeout 60s;
    • Notes :值爲0代表禁止長連接
  2. keepalive_requests :設定單次長連接所允許請求的資源的最大數量

    • Syntax :keepalive_requests #;
    • Default :100
    • Context :http, server, location
    • Example :keepalive_requests 70;
  3. keepalive_disable :設定對哪種瀏覽器禁用長連接

    • Syntax :keepalive_disable none | brower …;
    • Default :keepalive_disable msie6;
    • Context :http, server, location
    • Example :keepalive_disable msie6;
    • Notes :禁用是因爲某些瀏覽器不支持此功能
  4. send_timeout :設定向客戶端發送響應報文的超時時長

    • Syntax :send_timeout TIMEout;
    • Default :send_timeout 60s;
    • Context :http, server, location
    • Example :send_timeout 90s;
    • Notes :此選項是指兩次寫操作之間的間隔時長
  5. client_body_buffer_size :設定接收客戶端請求報文的body部分的緩衝區的大小

    • Syntax :client_body_buffer_size SIZE;
    • Default :client_header_buffer_size 1k
    • Context :http, server
    • Example :client_header_buffer_size 10k
    • Notes :超出此大小時,其將被暫存到磁盤上的由client_body_temp_path指令所定義的位置
  6. client_body_temp_path :設定用於存儲客戶端請求報文的body部分的臨時存儲路徑及子目錄結構和數量

    • Syntax :client_body_temp_path /TMP/PATH [level1 [level2 [level3]]];
    • Default :client_body_temp_path client_body_temp;
    • Context :http, server, location
    • Example :client_body_temp_path /var/tmp/client_body 1 2 2;
    • Notes :1:表示用一位16進制數字表示一級子目錄;0-f
      2:表示用2位16進程數字表示二級子目錄:00-ff
      2:表示用2位16進程數字表示三級子目錄:00-ff

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

  1. limit_rate :限制響應給客戶端的傳輸速率,單位是bytes/second
    • Syntax :limit_rate RATE;
    • Default :limit_rate 0;
    • Context :http, server, location, if in location
    • Example :
server {

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

    ...
}
  • Notes :值爲0表示不設限制

    1. limit_except :限定對指定客戶端不準使用的請求方法
  • Syntax :limit_except METHOD … {…};
  • Default :——
  • Context :location

- Example :

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

文件操作優化的配置

  1. aio :設定異步I/O功能的開關選項
    • Syntax :aio on | off | threads[=pool];
    • Default :aio off;
    • Context :http, server, location
    • Example :
location /video/ {
    aio            on;
    output_buffers 1 64k;
}
  1. direcrio :在Linux主機啓用O_DIRECT標記,

    • Syntax :directio size | off;
    • Default :directio off;
    • Context :http, server, location
    • Example :directio 4m;
    • Notes :當一個文件較大時,正在讀取的文件超過了指定的大小,啓用此選項
  2. open_file_cache :配置Nginx文件緩存

    • Syntax :open_file_cache off;
    • Syntax :open_file_cache max=N [inacitve=TIME];
    • Default :open_file_cache off;
    • Context :http, server, location
    • Example :open_file_cache max=1000 inactive=20s;
    • Notes1 :nginx可以緩存以下三種信息:

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

(2) 打開的目錄結構;

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

  • Notes2 :兩個參數的含義

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

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

  1. open_file_cache_valid :緩存有效性的檢查時間間隔

    • Syntax :open_file_cache_valid TIME;
    • Default :60s
    • Context :http, server, location
    • Example :open_file_cache_valid 100s;
  2. open_file_cache_min_uses :某一個緩存項的最少被命中次數

    • Syntax :open_file_cache_min_uses #;
    • Default :open_file_cache_min_uses 1;
    • Context :http, server, location
    • Example :open_file_cache_min_uses 3;
    • Notes :少於此項指令設定的值,在到達緩存檢查時間點後,該項緩存將會被刪除
  3. open_file_cache_errors :設定是否緩存錯誤的(否定的)查找結果

    • Syntax :open_file_cache_errors on | off;
    • Default :open_file_cache_errors off;
    • Context :http, server, location
    • Example :open_file_cache_errors on;
    • Notes :啓用此項指令,當某次查找結果爲錯誤時,該錯誤結果也會被緩存。
發佈了56 篇原創文章 · 獲贊 33 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章