溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Nginx常用配置詳解(二)——http協(xié)議配置塊

發(fā)布時(shí)間:2020-06-17 10:51:17 來(lái)源:網(wǎng)絡(luò) 閱讀:1221 作者:司徒剩堂 欄目:建站服務(wù)器

Nginx常用配置詳解(二)

http協(xié)議塊配置

http協(xié)議配置塊位于總體配置塊中,總體格式如下:

    http {
        ... ...
        server {
            ...
            server_name
            root
            location [OPERATOR] /uri/ {
                ...
            }
        }
        server {
            ...
        }
    }

http配置塊按功能分類,大致可以分為以下五類:

  1. 與套接字相關(guān)的配置

  2. 定義路徑相關(guān)的配置

  3. 定義客戶端請(qǐng)求的相關(guān)配置

  4. 對(duì)客戶端進(jìn)行限制的相關(guān)配置

一、與套接字相關(guān)的配置

server

Syntax: server { ... }
Default: —
Context: http

Sets configuration for a virtual server. There is no clear separation between IP-based (based on the IP address) and name-based (based on the “Host” request header field) virtual servers. Instead, the listen directives describe all addresses and ports that should accept connections for the server, and the server_name directive lists all server names.
設(shè)定一個(gè)虛擬主機(jī)。不需要明確區(qū)分基于ip和基于host的虛擬主機(jī)。相應(yīng)的,listen指令描述了此虛擬主機(jī)接收連接監(jiān)聽(tīng)的地址和端口,server_name字段描述了所有虛擬主機(jī)的名稱。

listen
Syntax: listen address[:port] [default_server] [ssl] [http2 | spdy] [proxy_protocol] [setfib=number] [fastopen=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on|off] [reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
        listen port [default_server] [ssl] [http2 | spdy] [proxy_protocol] [setfib=number] [fastopen=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on|off] [reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
        listen unix:path [default_server] [ssl] [http2 | spdy] [proxy_protocol] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
Default: listen *:80 | *:8000;
Context: server

Sets the address and port for IP, or the path for a UNIX-domain socket on which the server will accept requests. Both address and port, or only address or only port can be specified. An address may also be a hostname。
設(shè)定IP的addressport,或是設(shè)定服務(wù)器接收響應(yīng)的UNIX域套接字的path??梢酝瑫r(shí)設(shè)定addressport,或者僅僅設(shè)定address,僅僅設(shè)定port,address也可以是hostname。
例如

 listen 127.0.0.1:8000;
 listen 127.0.0.1;
 listen 8000;
 listen *:8000;
 listen localhost:8000;

UNIX-domain sockets (0.8.21) are specified with the “unix:” prefix:
UNIX域套接字需要在行首用unix:指明

  listen unix:/var/run/nginx.sock;

由于選項(xiàng)過(guò)多,且絕大多數(shù)目前階段應(yīng)用不上,簡(jiǎn)要解釋部分常用的

default_server

The default_server parameter, if present, will cause the server to become the default server for the specified address:port pair. If none of the directives have the default_server parameter then the first server with the address:port pair will be the default server for this pair.
設(shè)定當(dāng)前監(jiān)聽(tīng)的ip地址和端口為虛擬主機(jī),如果未明確指明默認(rèn)虛擬主機(jī),第一個(gè)虛擬主機(jī)成為該部分的默認(rèn)主機(jī)。

ssl

The ssl parameter (0.7.14) allows specifying that all connections accepted on this port should work in SSL mode. This allows for a more compact configuration for the server that handles both HTTP and HTTPS requests.
ssl字段允許指明從該端口接收的所有連接必須以SSL協(xié)議模式工作,無(wú)論接收的請(qǐng)求是HTTP協(xié)議的還是HTTPS協(xié)議。

http2

The http2 parameter (1.9.5) configures the port to accept HTTP/2 connections. Normally, for this to work the ssl parameter should be specified as well, but nginx can also be configured to accept HTTP/2 connections without SSL.
http2字段配置該端口可以接受http2協(xié)議的連接,通常http2協(xié)議需要指明ssl,但是nginx可以被配置成為接收不需要SSL協(xié)議的http2協(xié)議。

spdy

The spdy parameter (1.3.15-1.9.4) allows accepting SPDY connections on this port. Normally, for this to work the ssl parameter should be specified as well, but nginx can also be configured to accept SPDY connections without SSL.
spdy字段允許該端口接收SPDY連接,通常spdy協(xié)議需要指明ssl,但是nginx可以被配置成為接收不需要SSL協(xié)議的spdy協(xié)議。

proxy_protocol

The proxy_protocol parameter (1.5.12) allows specifying that all connections accepted on this port should use the PROXY protocol.
proxy_protocol字段允許指明該端口所有接收的連接使用PROXY協(xié)議。

backlog

sets the backlog parameter in the listen() call that limits the maximum length for the queue of pending connections. By default, backlog is set to -1 on FreeBSD, DragonFly BSD, and macOS, and to 511 on other platforms.
在listen()中設(shè)定backlog字段可以限制后援隊(duì)列長(zhǎng)度。默認(rèn)在FreeBSD, DragonFly BSD, 和 macOS平臺(tái)該值為-1,其他平臺(tái)該值為511

rcvbuf

sets the receive buffer size (the SO_RCVBUF option) for the listening socket.
設(shè)定監(jiān)聽(tīng)套接字的接收緩沖大小。

sndbuf

sets the send buffer size (the SO_SNDBUF option) for the listening socket.
設(shè)定監(jiān)聽(tīng)套接字的發(fā)送緩沖大小。

server_name

Syntax: server_name name ...;
Default: server_name "";
Context: server

Sets names of a virtual server, for example:
設(shè)定虛擬主機(jī)的名稱例如

 server {
     server_name example.com www.example.com;
 }

The first name becomes the primary server name.
第一個(gè)名稱成為虛擬主機(jī)的主名稱。
Server names can include an asterisk (“*”) replacing the first or last part of a name:
虛擬主機(jī)名稱可以在起始和末尾用通配符

*
替代

 server {
     server_name example.com *.example.com www.example.*;
 }

The first two of the names mentioned above can be combined in one:
前兩個(gè)地址可以縮寫成為一個(gè)

 server {
     server_name .example.com;
 }

It is also possible to use regular expressions in server names, preceding the name with a tilde (“~”):
還可以使用正則表達(dá)式匹配虛擬主機(jī)名稱,正則表達(dá)式前要用~

 server {
     server_name www.example.com ~^www\d+\.example\.com$;
 }

Regular expressions can contain captures (0.7.40) that can later be used in other directives:
正則表達(dá)式的分組可以用于其它字段。

 server {
     server_name ~^(www\.)?(.+)$;

     location / {
         root /sites/$2;
     }
 }

 server {
     server_name _;

     location / {
         root /sites/default;
     }
 }

Named captures in regular expressions create variables (0.8.25) that can later be used in other directives:
正則表達(dá)式匹配的優(yōu)先級(jí)要低于其他字段。

server {
    server_name ~^(www\.)?(?<domain>.+)$;

    location / {
        root /sites/$domain;
    }
}

server {
    server_name _;

    location / {
        root /sites/default;
    }
}

If the directive’s parameter is set to “$hostname” (0.9.4), the machine’s hostname is inserted.
如果設(shè)定為變量$hostname會(huì)插入機(jī)器的hostname。(0.9.4之后的版本可用)
It is also possible to specify an empty server name (0.7.11):
也可以插入空的虛擬機(jī)主機(jī)名稱(0.7.11之后的版本可用)

server {
    server_name www.example.com "";
}

It allows this server to process requests without the “Host” header field — instead of the default server — for the given address:port pair. This is the default setting.
允許虛擬主機(jī)響應(yīng)沒(méi)有Host頭部的,該頭部將會(huì)替換成默認(rèn)虛擬主機(jī),給予一個(gè)ip地址和端口段。該項(xiàng)為默認(rèn)設(shè)置。

Before 0.8.48, the machine’s hostname was used by default. 
0.8.48版本前,機(jī)器的hostname為默認(rèn)的。

During searching for a virtual server by name, if the name matches more than one of the specified variants, (e.g. both a wildcard name and regular expression match), the first matching variant will be chosen, in the following order of priority:
當(dāng)搜尋一個(gè)虛擬的主機(jī)的名稱時(shí)。如果該名稱可以匹配多個(gè)字段(包括通配符和正則表達(dá)式的字段),優(yōu)先匹配原則如下:

the exact name
the longest wildcard name starting with an asterisk, e.g. “*.example.com”
the longest wildcard name ending with an asterisk, e.g. “mail.*”
the first matching regular expression (in order of appearance in the configuration file)

1.字符串精確匹配
2.左側(cè)*通配符
3.右側(cè)*通配符
4.正則表達(dá)式

tcp_nodelay

Syntax: tcp_nodelay on | off;
Default: tcp_nodelay on;
Context: http, server, location

Enables or disables the use of the TCP_NODELAY option. The option is enabled only when a connection is transitioned into the keep-alive state.
啟用或禁用TCP_NODELAY設(shè)置,當(dāng)連接轉(zhuǎn)換為長(zhǎng)連接狀態(tài),這個(gè)選項(xiàng)必須啟用。

sendfile

Syntax: sendfile on | off;
Default: sendfile off;
Context: http, server, location, if in location

Enables or disables the use of sendfile().
In this configuration, sendfile() is called with the SF_NODISKIO flag which causes it not to block on disk I/O, but, instead, report back that the data are not in memory. nginx then initiates an asynchronous data load by reading one byte. On the first read, the FreeBSD kernel loads the first 128K bytes of a file into memory, although next reads will only load data in 16K chunks. This can be changed using the read_ahead directive.
啟用或禁用sendfile()功能。
在此項(xiàng)配置中,sentfile()被稱為SF_NODISKIO標(biāo)記,該標(biāo)記引起不阻塞在磁盤I/O,相應(yīng)的報(bào)告數(shù)據(jù)不在內(nèi)存中。nginx然后會(huì)啟用一個(gè)異步加載數(shù)據(jù)讀取一個(gè)字節(jié)。第一次閱讀,F(xiàn)reeBSD內(nèi)容加載文件的第一個(gè)128K字節(jié)至內(nèi)存,盡管接下來(lái)的讀取只會(huì)在16K塊中加載數(shù)據(jù)。可以在read_ahead指令中修改此條目。

tcp_nopush

Syntax: tcp_nopush on | off;
Default: tcp_nopush off;
Context: http, server, location

Enables or disables the use of the TCP_NOPUSH socket option on FreeBSD or the TCP_CORK socket option on Linux. The options are enabled only when sendfile is used. Enabling the option allows
禁用或啟用TCP_NOPUSH套接字的使用,其工作于FreeBSD系統(tǒng)或Linux系統(tǒng)的TCP_CORK套接字選項(xiàng)。這個(gè)宣講只有在sendfile使用時(shí)啟用,啟用這個(gè)選項(xiàng)允許

  • sending the response header and the beginning of a file in one packet, on Linux and FreeBSD 4.;
    在包起始位置發(fā)送響應(yīng)報(bào)文頭部(工作于Linux和FreeBSD 4.

  • sending a file in full packets.
    在完整的數(shù)據(jù)包中發(fā)送文件

二、定義路徑相關(guān)的配置

root

Syntax: root path;
Default: root html;
Context: http, server, location, if in location

Sets the root directory for requests. For example, with the following configuration
設(shè)置響應(yīng)的根目錄,例如使用如下配置
location /i/ {
root /data/w3;
}

The /data/w3/i/top.gif file will be sent in response to the “/i/top.gif” request.
/data/w3/i/top.gif文件會(huì)發(fā)送到/i/top.gif響應(yīng)報(bào)文中
The path value can contain variables, except $document_root and $realpath_root.
這個(gè)值可以是變量,$document_root$realpath_root不可以使用。

root指令取代的根目錄在location目錄中替代最左端的/

alias

設(shè)定網(wǎng)站別名,用法基本與root相同。
alias指令取代的根目錄在location目錄中替代至最右端的/

location

Syntax: location [ = | ~ | ~* | ^~ ] uri { ... }
        location @name { ... }
Default: —
Context: server, location

Sets configuration depending on a request URI.
根據(jù)請(qǐng)求的URI設(shè)置配置。
The matching is performed against a normalized URI, after decoding the text encoded in the “%XX” form, resolving references to relative path components “.” and “..”, and possible compression of two or more adjacent slashes into a single slash.
匹配時(shí)針對(duì)規(guī)范化的URI執(zhí)行的,解碼了% XX格式的文本,解析相對(duì)路徑的引用...,壓縮兩個(gè)或更多相鄰的/至一個(gè)/
A location can either be defined by a prefix string, or by a regular expression. Regular expressions are specified with the preceding “~*” modifier (for case-insensitive matching), or the “~” modifier (for case-sensitive matching). To find location matching a given request, nginx first checks locations defined using the prefix strings (prefix locations). Among them, the location with the longest matching prefix is selected and remembered. Then regular expressions are checked, in the order of their appearance in the configuration file. The search of regular expressions terminates on the first match, and the corresponding configuration is used. If no match with a regular expression is found then the configuration of the prefix location remembered earlier is used.
location可以由前綴字符串定義,也可以由正則表達(dá)式定義。正在表達(dá)式用~×表示不區(qū)分大小寫匹配,用~表示區(qū)分大小寫匹配。根據(jù)被給予的請(qǐng)求報(bào)文尋找location時(shí),nginx優(yōu)先查詢使用前置字符串定義的location。匹配字符串時(shí)最長(zhǎng)匹配的字符串將會(huì)被選擇,并且被記住。然后會(huì)按照配置文件中出現(xiàn)的次序檢查正則表達(dá)式。匹配第一次正則表達(dá)式后會(huì)終止,并使用相應(yīng)的配置。如果沒(méi)有發(fā)現(xiàn)合適的正則表達(dá)式匹配,則會(huì)使用之前記住的字符串匹配的信息。
location blocks can be nested, with some exceptions mentioned below.
location配置塊可以嵌套。

Regular expressions can contain captures (0.7.40) that can later be used in other directives.
正則表達(dá)式可以捕獲分組信息(0.7.40),之后用在其他指令
If the longest matching prefix location has the “^~” modifier then regular expressions are not checked.
如果最長(zhǎng)匹配字段有^~修飾符,不檢查正則匹配。
Also, using the “=” modifier it is possible to define an exact match of URI and location. If an exact match is found, the search terminates. For example, if a “/” request happens frequently, defining “l(fā)ocation = /” will speed up the processing of these requests, as search terminates right after the first comparison. Such a location cannot obviously contain nested locations.
同樣的,使用=修飾符可以定義一個(gè)精確的URI和location匹配,如果發(fā)現(xiàn)精確匹配,查詢終止。例如:如果“/”請(qǐng)求頻繁出現(xiàn),定義“l(fā)ocation = /”可以在第一次比較后終止查詢,從而加速這些請(qǐng)求的進(jìn)程。這種location不能嵌套location。

Let’s illustrate the above by an example:
用下面的例子舉例說(shuō)明

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

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

location ~* \.(gif|jpg|jpeg)$ {
    [ 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 “/p_w_picpaths/1.gif” request will match configuration D, and the “/documents/1.jpg” request will match configuration E.
“/”請(qǐng)求會(huì)匹配到A,
“/index.html”會(huì)匹配到B,
“/documents/document.html”請(qǐng)求會(huì)匹配到C,
“/p_w_picpaths/1.gif”會(huì)匹配到D,
“/documents/1.jpg”會(huì)匹配到E。
The “@” prefix defines a named location. Such a location is not used for a regular request processing, but instead used for request redirection. They cannot be nested, and cannot contain nested locations.
“@”定義名稱location。這樣的location不用于一個(gè)普通請(qǐng)求,而用于請(qǐng)求重定向。他們不能被嵌套,也不能嵌套其他location。
If a location is defined by a prefix string that ends with the slash character, and requests are processed by one of proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, or memcached_pass, then the special processing is performed. In response to a request with URI equal to this string, but without the trailing slash, a permanent redirect with the code 301 will be returned to the requested URI with the slash appended. If this is not desired, an exact match of the URI and location could be defined like this:
如果一個(gè)location定義字符串匹配時(shí)以/結(jié)尾,而且請(qǐng)求被proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, memcached_pass中的一個(gè)處理,將會(huì)執(zhí)行特殊的處理方式。響應(yīng)請(qǐng)求URI等于這個(gè)字符串時(shí),不需要尾部有/,將會(huì)返回一個(gè)301狀態(tài)碼的永久重定向,并攜帶一個(gè)/。如果不需要的話可以像如下方法額外添加URI和location的定義。

location /user/ {
    proxy_pass http://user.example.com;
}

location = /user {
    proxy_pass http://login.example.com;
}

index

Syntax: index file ...;
Default: index index.html;
Context: http, server, location

Defines files that will be used as an index. The file name can contain variables. Files are checked in the specified order. The last element of the list can be a file with an absolute path. Example:
定義被用作索引的文件。該文件名可以包含變量。多文件按順序檢查。列表最后元素可以是一個(gè)包含絕對(duì)路徑文件。例如

index index.$geo.html index.0.html /index.html;

It should be noted that using an index file causes an internal redirect, and the request can be processed in a different location. For example, with the following configuration:
值得注意的是,使用索引文件會(huì)造成內(nèi)部重定向,請(qǐng)求會(huì)被指向不同的location。如下面例子所示

location = / {
    index index.html;
}

location / {
    ...
}

a “/” request will actually be processed in the second location as “/index.html”.
一個(gè)“/”請(qǐng)求事實(shí)首先被解析成為index.html,而后被解析到第二location中。

error_page

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

Defines the URI that will be shown for the specified errors. A uri value can contain variables.
定義顯示指定錯(cuò)誤的URI。uri值可以使用變量。

Example:
例如

error_page 404             /404.html;
error_page 500 502 503 504 /50x.html;

This causes an internal redirect to the specified uri with the client request method changed to “GET” (for all methods other than “GET” and “HEAD”).
這將導(dǎo)致將內(nèi)部重定向到指定的uri,而客戶端請(qǐng)求方法改為“GET”(除“GET”和“HEAD”之外的所有方法)。
Furthermore, it is possible to change the response code to another using the “=response” syntax, for example:
此外,還可以使用“=response”語(yǔ)法將狀態(tài)響應(yīng)代碼更改為另一個(gè),例如:

error_page 404 =200 /empty.gif;

If an error response is processed by a proxied server or a FastCGI/uwsgi/SCGI server, and the server may return different response codes (e.g., 200, 302, 401 or 404), it is possible to respond with the code it returns:
如果代理服務(wù)器或FastCGI / uwsgi / SCGI服務(wù)器處理錯(cuò)誤響應(yīng),服務(wù)器可能會(huì)返回不同的響應(yīng)代碼,(例如200, 302, 401 或 404),可以響應(yīng)返回碼。

error_page 404 = /404.php;

If there is no need to change URI and method during internal redirection it is possible to pass error processing into a named location:
如果在內(nèi)部重定向中不需要更改URI和方法,則可以將錯(cuò)誤處理傳入指定的位置:

location / {
    error_page 404 = @fallback;
}

location @fallback {
    proxy_pass http://backend;
}

If uri processing leads to an error, the status code of the last occurred error is returned to the client.
如果uri處理導(dǎo)致錯(cuò)誤,那么最后一個(gè)發(fā)生錯(cuò)誤的狀態(tài)代碼將返回給客戶端。
It is also possible to use URL redirects for error processing:
也可以使用URL重定向錯(cuò)誤處理。

error_page 403      http://example.com/forbidden.html;
error_page 404 =301 http://example.com/notfound.html;

In this case, by default, the response code 302 is returned to the client. It can only be changed to one of the redirect status codes (301, 302, 303, 307, and 308).
在這種情況下,默認(rèn)情況下,響應(yīng)代碼302被返回給客戶端。它只能更改為一個(gè)重定向狀態(tài)碼(301、302、303、307和308)。
These directives are inherited from the previous level if and only if there are no error_page directives defined on the current level.
只有在當(dāng)前級(jí)別沒(méi)有定義error_page指令的情況下,將從上一級(jí)繼承error_page信息。

try_files

Syntax: try_files file ... uri;
        try_files file ... =code;
Default: —
Context: server, location

Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the file parameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”. If none of the files were found, an internal redirect to the uri specified in the last parameter is made. For example:
檢查指定順序文件是否存在,使用第一個(gè)找到的文件進(jìn)行處理,該處理在當(dāng)前上下文執(zhí)行。根據(jù)root和alias指令從文件參數(shù)構(gòu)建文件路徑??梢詸z查目錄是否存在,需要后置/例如“$uri/”。如果未找到文件,內(nèi)部重定向到最后一個(gè)參數(shù)中指定的uri。例如:

location /p_w_picpaths/ {
    try_files $uri /p_w_picpaths/default.gif;
}

location = /p_w_picpaths/default.gif {
    expires 30s;
}

三、定義客戶端請(qǐng)求的相關(guān)配置

keepalive_timeout

Syntax: keepalive_timeout timeout [header_timeout];
Default: keepalive_timeout 75s;
Context: http, server, location

The first parameter sets a timeout during which a keep-alive client connection will stay open on the server side. The zero value disables keep-alive client connections. The optional second parameter sets a value in the “Keep-Alive: timeout=time” response header field. Two parameters may differ.
第一個(gè)字段設(shè)定了長(zhǎng)連接客戶端打開服務(wù)端的延遲,0值禁用長(zhǎng)連接。第二字段設(shè)定HEAD字段中“Keep-Alive: timeout=time”time值。兩個(gè)字段可以不同。
The “Keep-Alive: timeout=time” header field is recognized by Mozilla and Konqueror. MSIE closes keep-alive connections by itself in about 60 seconds.
Mozilla和Konqueror瀏覽器認(rèn)可HEADER頭字段中 “Keep-Alive: timeout=time”值。MSIE長(zhǎng)連接60秒后自動(dòng)關(guān)閉。

keepalive_requests

Syntax: keepalive_requests number;
Default: keepalive_requests 100;
Context: http, server, location
This directive appeared in version 0.8.0.

Sets the maximum number of requests that can be served through one keep-alive connection. After the maximum number of requests are made, the connection is closed.
設(shè)定請(qǐng)求的長(zhǎng)連接的最大值,一旦超過(guò)最大值,連接關(guān)閉。

keepalive_disable

Syntax: keepalive_disable none | browser ...;
Default: keepalive_disable msie6;
Context: http, server, location

Disables keep-alive connections with misbehaving browsers. The browser parameters specify which browsers will be affected. The value msie6 disables keep-alive connections with old versions of MSIE, once a POST request is received. The value safari disables keep-alive connections with Safari and Safari-like browsers on macOS and macOS-like operating systems. The value none enables keep-alive connections with all browsers.
在不適合的瀏覽器訪問(wèn)時(shí)禁用長(zhǎng)連接功能。browser指明那個(gè)瀏覽器收到影響。msie6值表示一旦收到老版本的MSIE瀏覽器POST請(qǐng)求,禁用長(zhǎng)連接功能。safari值表示macOS和macOS類的操作系統(tǒng)上的Safari和類Safari的瀏覽器禁用長(zhǎng)連接功能。none值表示所有瀏覽器啟用長(zhǎng)連接功能。

send_timeout

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

Sets a timeout for transmitting a response to the client. The timeout is set only between two successive write operations, not for the transmission of the whole response. If the client does not receive anything within this time, the connection is closed.
設(shè)定一個(gè)傳送響應(yīng)報(bào)文到客戶端的超時(shí)時(shí)間。該超時(shí)時(shí)間只是兩個(gè)寫操作之間的,不應(yīng)用于全部響應(yīng)。如果客戶端在這個(gè)時(shí)間不接受,連接關(guān)閉。

client_body_buffer_size

Syntax: client_body_buffer_size size;
Default: client_body_buffer_size 8k|16k;
Context: http, server, location

Sets buffer size for reading client request body. In case the request body is larger than the buffer, the whole body or only its part is written to a temporary file. By default, buffer size is equal to two memory pages. This is 8K on x86, other 32-bit platforms, and x86-64. It is usually 16K on other 64-bit platforms.
設(shè)定讀取客戶機(jī)請(qǐng)求主體設(shè)置緩沖區(qū)大小,萬(wàn)一請(qǐng)求主體大于緩沖區(qū),整個(gè)主體或主體的某一部分被寫到一個(gè)臨時(shí)文件。默認(rèn)情況下,緩沖區(qū)大小等于兩個(gè)內(nèi)存頁(yè),32位系統(tǒng)為8K,64位系統(tǒng)為16K。

client_body_temp_path

Syntax: client_body_temp_path path [level1 [level2 [level3]]];
Default: client_body_temp_path client_body_temp;
Context: http, server, location

Defines a directory for storing temporary files holding client request bodies. Up to three-level subdirectory hierarchy can be used under the specified directory. For example, in the following configuration
定義用于存儲(chǔ)客戶端請(qǐng)求主體的臨時(shí)文件的目錄。在指定的目錄下可以使用至多3級(jí)的子目錄層次結(jié)構(gòu)。例如,在以下配置中

client_body_temp_path /spool/nginx/client_temp 1 2;

a path to a temporary file might look like this:
一個(gè)臨時(shí)文件文件可能根如下文件類似:

/spool/nginx/client_temp/7/45/00000123457

client_body_temp_path /var/tmp/client_body 2 1 1
1:表示用一位16進(jìn)制數(shù)字表示一級(jí)子目錄;0-f
2:表示用2位16進(jìn)程數(shù)字表示二級(jí)子目錄:00-ff
3:表示用2位16進(jìn)程數(shù)字表示三級(jí)子目錄:00-ff

四、對(duì)客戶端進(jìn)行限制的相關(guān)配置

limit_rate

Syntax: limit_rate rate;
Default: limit_rate 0;
Context: http, server, location, if in location

Limits the rate of response transmission to a client. The rate is specified in bytes per second. The zero value disables rate limiting. The limit is set per a request, and so if a client simultaneously opens two connections, the overall rate will be twice as much as the specified limit.
限制傳輸?shù)娇蛻舳说捻憫?yīng)速率。速率以每秒bytes指定。0值表示不限制。限制是根據(jù)每個(gè)請(qǐng)求設(shè)置的,如果一個(gè)客戶端同時(shí)打開兩個(gè)連接,總限制為指明限制的兩倍。
Rate limit can also be set in the $limit_rate variable. It may be useful in cases where rate should be limited depending on a certain condition:
速度限制同樣可以在$limit_rate變量中設(shè)定。當(dāng)限制需要基于確定的情況時(shí)也許有用:

server {

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

    ...
}

Rate limit can also be set in the “X-Accel-Limit-Rate” header field of a proxied server response. This capability can be disabled using the proxy_ignore_headers, fastcgi_ignore_headers, uwsgi_ignore_headers, and scgi_ignore_headers directives.
限速也可以在代理服務(wù)器響應(yīng)中“X-Accel-Limit-Rate” HEARER字段中設(shè)定??梢允褂胮roxy_ignore_header、fastcgi_ignore_header、uwsgi_ignore_header和scgi_ignore_header指令禁用此功能。

limit_except

Syntax: limit_except method ... { ... }
Default: —
Context: location

Limits allowed HTTP methods inside a location. The method parameter can be one of the following: GET, HEAD, POST, PUT, DELETE, MKCOL, COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, LOCK, UNLOCK, or PATCH. Allowing the GET method makes the HEAD method also allowed. Access to other methods can be limited using the ngx_http_access_module and ngx_http_auth_basic_module modules directives:
限制允許的HTTP方法訪問(wèn)一個(gè)location。這個(gè)方法字段可以是GET, HEAD, POST, PUT, DELETE, MKCOL, COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, LOCK, UNLOCK, PATCH中的一個(gè).允許GET方法也會(huì)使HEAD方法可用。允許其他方法需要用到ngx_http_access_modulengx_http_auth_basic_module模塊中的指令。

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

Please note that this will limit access to all methods except GET and HEAD.
注:這將限制除了GETHEAD之外的所有方法。

五、 文件操作優(yōu)化的配置

aio

Syntax: aio on | off | threads[=pool];
Default: aio off;
Context: http, server, location
This directive appeared in version 0.8.11.

Enables or disables the use of asynchronous file I/O (AIO) on FreeBSD and Linux:
在FreeBSD、Linux系統(tǒng)中啟用或禁用異步文件I/O

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

On FreeBSD, AIO can be used starting from FreeBSD 4.3. Prior to FreeBSD 11.0, AIO can either be linked statically into a kernel:
在FreeBSD上,F(xiàn)reeBSD 4.3以后開始支持AIO。FreeBSD 11.0之前,AIO可以靜態(tài)鏈接到內(nèi)核。

options VFS_AIO

或動(dòng)態(tài)加載成為一個(gè)內(nèi)核模塊

kldload aio

On Linux, AIO can be used starting from kernel version 2.6.22. Also, it is necessary to enable directio, or otherwise reading will be blocking:
Linux系統(tǒng)上,Linux2.6.22之后支持AIO,同樣的必須啟用directio,否則讀取會(huì)被阻塞。

location /video/ {
    aio            on;
    directio       512;
    output_buffers 1 128k;
}

On Linux, directio can only be used for reading blocks that are aligned on 512-byte boundaries (or 4K for XFS). File’s unaligned end is read in blocking mode. The same holds true for byte range requests and for FLV requests not from the beginning of a file: reading of unaligned data at the beginning and end of a file will be blocking.
Linux系統(tǒng)上,directio只能用于讀取512K對(duì)齊的塊(XFS文件系統(tǒng)為4K)。文件未對(duì)齊的結(jié)尾在讀取時(shí)處于阻塞模式。對(duì)于字節(jié)范圍請(qǐng)求和FLV請(qǐng)求,同樣適用于文件的開頭:在文件開始和結(jié)束時(shí)讀取未對(duì)齊的數(shù)據(jù)將被阻塞。
When both AIO and sendfile are enabled on Linux, AIO is used for files that are larger than or equal to the size specified in the directio directive, while sendfile is used for files of smaller sizes or when directio is disabled.
Linux系統(tǒng)上同時(shí)啟用AIO和sendfile時(shí),AIO作用域大于或等于directio指令指明的文件大小。sendfile用于小于directio指令指明的文件大小,或者directio禁用的情況。

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

Finally, files can be read and sent using multi-threading (1.7.11), without blocking a worker process:
最后,文件的讀取和發(fā)送可以不被一個(gè)worker進(jìn)程阻塞,使用多線程模式

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

Read and send file operations are offloaded to threads of the specified pool. If the pool name is omitted, the pool with the name “default” is used. The pool name can also be set with variables:
讀取和發(fā)送文件操作將卸載到指定池的線程。如果這個(gè)池的名稱是省略的,這個(gè)池將使用“default” 作為名稱。池名稱可以同樣用變量設(shè)置

aio threads=pool$disk;

By default, multi-threading is disabled, it should be enabled with the —with-threads configuration parameter. Currently, multi-threading is compatible only with the epoll, kqueue, and eventport methods. Multi-threaded sending of files is only supported on Linux.
默認(rèn)情況下,多線程被禁用,可以使用--with-threads控制字段啟用。一般來(lái)說(shuō),多線程僅兼容epoll, kqueue, eventport方法。僅Linux系統(tǒng)支持多線程發(fā)送文件。

directio

Syntax: directio size | off;
Default: directio off;
Context: http, server, location

This directive appeared in version 0.7.7.

Enables the use of the O_DIRECT flag (FreeBSD, Linux), the F_NOCACHE flag (macOS), or the directio() function (Solaris), when reading files that are larger than or equal to the specified size. The directive automatically disables (0.7.15) the use of sendfile for a given request. It can be useful for serving large files:
當(dāng)讀取的文件大于指定塊時(shí),啟用O_DIRECT標(biāo)記(FreeBSD, Linux),F(xiàn)_NOCACHE標(biāo)記(macOS)或是directio()函數(shù)(Solaris)。該指令自動(dòng)禁用(0.7.15)sendfile對(duì)給定請(qǐng)求的使用。發(fā)送大文件時(shí)使用:

directio 4m;

or when using aio on Linux.
或在Linux系統(tǒng)使用aio。

open_file_cache

Syntax: open_file_cache off;
        open_file_cache max=N [inactive=time];
Default: open_file_cache off;
Context: http, server, location

Configures a cache that can store:
配置一個(gè)可以存儲(chǔ)如下信息的緩存:

  • open file descriptors, their sizes and modification times;

  • information on existence of directories;

  • file lookup errors, such as “file not found”, “no read permission”, and so on. (Caching of errors should be enabled separately by the open_file_cache_errors directive. )
    -

  • open file 描述符,他們的大小和修改時(shí)間

  • 存在的目錄信息

  • 文件查詢錯(cuò)誤,如“file not found”,“no read permission”等等(錯(cuò)誤緩存需要從open_file_cache_errors單獨(dú)啟用。)

The directive has the following parameters:
該指令有如下字段
max
sets the maximum number of elements in the cache; on cache overflow the least recently used (LRU) elements are removed;
設(shè)定緩存中元素?cái)?shù)量的最大值,當(dāng)溢出時(shí)使用LRU算法。
inactive
defines a time after which an element is removed from the cache if it has not been accessed during this time; by default, it is 60 seconds;
定義一段時(shí)間,如果這段時(shí)間某元素未被訪問(wèn),則從緩存中移除該元素。默認(rèn)情況下,時(shí)長(zhǎng)60秒。
off
disables the cache
禁用緩存
Example:
例如

open_file_cache          max=1000 inactive=20s;
open_file_cache_valid    30s;
open_file_cache_min_uses 2;
open_file_cache_errors   on;
open_file_cache_errors
Syntax: open_file_cache_errors on | off;
Default: open_file_cache_errors off;
Context: http, server, location

Enables or disables caching of file lookup errors by open_file_cache.
啟用或禁用open_file_cache中的文件查看錯(cuò)誤。

open_file_cache_min_uses
Syntax: open_file_cache_min_uses number;
Default: open_file_cache_min_uses 1;
Context: http, server, location

Sets the minimum number of file accesses during the period configured by the inactive parameter of the open_file_cache directive, required for a file descriptor to remain open in the cache.
設(shè)定在open_file_cache中inactive配置的期間文件的最小訪問(wèn)數(shù)值,要求在緩存中保持文件描述符保持打開狀態(tài)。

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

Sets a time after which open_file_cache elements should be validated.
設(shè)定緩存項(xiàng)有效性的檢查時(shí)間間隔。


向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI