Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Detailed explanation of Nginx Common configuration (2)-- http Protocol configuration Block

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

Detailed explanation of Nginx common configuration (2) http protocol block configuration

The http protocol configuration block is located in the overall configuration block and the overall format is as follows:

Http {...... Server {... Server_name root location [OPERATOR] / uri/ {...}} server {...}}

Http configuration blocks are classified by function and can be roughly divided into the following five categories:

Socket-related configuration

Define path-related configurations

Define the relevant configuration of client request

Configuration related to restrictions on clients

1. Socket-related configuration serverSyntax: 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.

Set up a virtual host. There is no need to clearly distinguish between ip-based and host-based virtual hosts. Accordingly, the listen directive describes the address and port on which this virtual host receives connection listening, and the server_name field describes the names of all virtual hosts.

ListenSyntax: 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] [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 X 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 .

Set the address and port of the IP, or set the path of the UNIX domain socket that the server receives the response. You can set both address and port, or just set address, or just set port,address or hostname.

For example

Listen 127.0.0.1 listen 8000; listen 127.0.1; listen 8000; listen *: 8000; listen localhost:8000

UNIX-domain sockets (0.8.21) are specified with the "unix:" prefix:

The UNIX domain socket needs to start the line with unix: indicates

Listen unix:/var/run/nginx.sock

As there are too many options, and most of them are not available at this stage, briefly explain some of the commonly used

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.

Set the current listening ip address and port as the virtual host, and if the default virtual host is not clearly specified, the first virtual host becomes the default host for this part.

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.

The ssl field allows you to indicate that all connections received from that port must work in SSL protocol mode, regardless of whether the request received is HTTP or HTTPS.

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.

The port is configured in the http2 field to accept connections to the http2 protocol, usually the http2 protocol needs to specify ssl, but nginx can be configured to receive http2 protocols that do not require the SSL protocol.

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.

The spdy field allows the port to receive SPDY connections, usually the spdy protocol needs to specify ssl, but nginx can be configured to receive spdy protocols that do not require the SSL protocol.

Proxy_protocol

The proxy_protocol parameter (1.5.12) allows specifying that all connections accepted on this port should use the PROXY protocol.

The proxy_protocol field allows you to indicate that all connections received on that port use the PROXY protocol.

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.

Setting the backlog field in listen () limits the length of the backup queue. The default value is-1 for FreeBSD, DragonFly BSD, and macOS platforms, and 511 for other platforms

Rcvbuf

Sets the receive buffer size (the SO_RCVBUF option) for the listening socket.

Sets the receive buffer size of the listening socket.

Sndbuf

Sets the send buffer size (the SO_SNDBUF option) for the listening socket.

Sets the send buffer size of the listening socket.

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

Sets names of a virtual server, for example:

Set the name of the virtual host, for example

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

The first name becomes the primary server name.

The first name becomes the primary name of the virtual host.

Server names can include an asterisk ("*") replacing the first or last part of a name:

Virtual host names can use wildcards at the beginning and end

*

Substitution

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

The first two of the names mentioned above can be combined in one:

The first two addresses can be abbreviated to a

Server {server_name .example.com;}

It is also possible to use regular expressions in server names, preceding the name with a tilde ("~"):

You can also use regular expressions to match virtual host names, using ~ before regular expressions.

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:

Grouping of regular expressions can be used in other fields.

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:

Regular expression matching takes precedence over other fields.

Server {server_name ~ ^ (www\.) (?. +) $; 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.

If set to the variable $hostname, it will be inserted into the machine's hostname. (versions after 0.9.4 are available)

It is also possible to specify an empty server name (0.7.11):

You can also insert an empty virtual machine host name (versions after 0.7.11 are available)

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.

If the virtual host is allowed to respond without a Host header, the header will be replaced with the default virtual host, giving an ip address and port segment. This is the default setting.

Before 0.8.48, the machine's hostname was used by default. Prior to version 0.8.48, the hostname of the machine was the default.

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:

When searching for the name of a virtual host. If the name can match multiple fields (including fields of wildcards and regular expressions), the priority matching principle is as follows:

The exact namethe 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. The string matches exactly 2. Left * wildcard 3. Right * wildcard 4. Regular expression tcp_nodelaySyntax: 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.

Enables or disables the TCP_NODELAY setting, which must be enabled when the connection transitions to the persistent connection state.

SendfileSyntax: 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 is called with the SF_NODISKIO flag which causes it not to block on disk 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.

Enable or disable the sendfile () feature.

In this configuration, sentfile () is called the SF_NODISKIO tag, which causes non-blocking on disk Imax O, and the corresponding report data is not in memory. Nginx then enables an asynchronous load of data to read a byte. The first time you read it, the FreeBSD content loads the first 128K bytes of the file into memory, although subsequent reads only load data in 16K blocks. This entry can be modified in the read_ahead directive.

Tcp_nopushSyntax: 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

Disables or enables the use of TCP_NOPUSH sockets, which work on FreeBSD systems or TCP_CORK sockets options on Linux systems. This announcement is enabled only when sendfile is used, and enabling this option allows

Sending the response header and the beginning of a file in one packet, on Linux and FreeBSD 4.

Send the response header at the start of the packet (working on Linux and FreeBSD 4.)

Sending a file in full packets.

Send a file in a complete packet

Define path-related configurations rootSyntax: root path;Default: root html;Context: http, server, location, if in location

Sets the root directory for requests. For example, with the following configuration

Set the root directory of the response, for example, using the following configuration

Location / i/ {

Root / data/w3

}

The / data/w3/i/top.gif file will be sent in response to the "/ i/top.gif" request.

The / data/w3/i/top.gif file is sent to the / i/top.gif response message

The path value can contain variables, except $document_root and $realpath_root.

This value can be a variable, but $document_root and $realpath_root cannot be used.

The root directory replaced by the root directive replaces the leftmost / in the location directory

Alias

Set the website alias, using basically the same as root.

The root directory replaced by the alias directive is replaced by the rightmost / in the location directory

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

Sets configuration depending on a request URI.

Configure according to the requested URI settings.

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.

The match is performed for the normalized URI, decoding the text in% XX format and parsing references to the relative path. And, compress two or more adjacent / to one /

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 can be defined by a prefix string or by a regular expression. The expression is expressed with ~ × for case-insensitive matching and ~ for case-sensitive matching. When looking for a location based on the given request message, the nginx first query uses the location defined by the prestring. When matching a string, the longest matching string will be selected and remembered. The regular expressions are then checked in the order in which they appear in the configuration file. Matching the first regular expression terminates and uses the appropriate configuration. If no appropriate regular expression match is found, the string matching information remembered earlier is used.

Location blocks can be nested, with some exceptions mentioned below.

Location configuration blocks can be nested.

Regular expressions can contain captures (0.7.40) that can later be used in other directives.

Regular expressions can capture packet information (0.7.40) and then use it in other instructions

If the longest matching prefix location has the "^ ~" modifier then regular expressions are not checked.

If the longest matching field has a ^ ~ modifier, the regular match is not checked.

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 "location = /" will speed up the processing of these requests, as search terminates right after the first comparison. Such a location cannot obviously contain nested locations.

Similarly, you can define an exact URI and location match using the = modifier, and if an exact match is found, the query is terminated. For example, if "/" requests occur frequently, defining "location = /" can terminate the query after the first comparison, thus speeding up the process of these requests. This kind of location cannot nest location.

Let's illustrate the above by an example:

Use the following example to illustrate

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.

The "/" request will match to A

"/ index.html" will match to B.

The "/ documents/document.html" request will match to C

"/ p_w_picpaths/1.gif" will match to D.

"/ documents/1.jpg" matches to 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.

"@" defines the name location. Such a location is not used for a normal request, but for request redirection. They cannot be nested, nor can they nest other 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:

If a location definition string matches with a /, and the request is processed by one of proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, memcached_pass, special processing will be performed. When the response request URI equals this string, no trailing / is required, and a permanent redirection of the 301 status code will be returned with a /. If not, you can add additional definitions of URI and location as shown below.

Location / user/ {proxy_pass http://user.example.com;}location = / user {proxy_pass http://login.example.com;}indexSyntax: 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:

Defines the file to be used as an index. The file name can contain variables. Multiple files are checked sequentially. The last element of the list can be a file that contains absolute paths. For example

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:

It is worth noting that the use of index files results in internal redirects and requests are directed to different location. As shown in the following example

Location = / {index index.html;} location / {...}

A "/" request will actually be processed in the second location as "/ index.html".

A "/" request fact is first parsed into an index.html and then parsed into a second location.

Error_pageSyntax: 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.

Defines the URI that displays the specified error. Variables can be used for uri values.

Example:

For example

Error_page 404 / 404. Htmlbomacherism 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")

This causes internal redirection to the specified uri, and the client request method is changed to "GET" (all methods except "GET" and "HEAD").

Furthermore, it is possible to change the response code to another using the "= response" syntax, for example:

In addition, you can use the "= response" syntax to change the status response code to another, for example:

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:

If the proxy server or FastCGI / uwsgi / SCGI server handles the error response, the server may return a different response code (for example, 200302401 or 404), which can respond to the return code.

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:

If you do not need to change the URI and method in the internal redirection, you can pass error handling into the specified location:

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.

If the uri processing causes an error, the last status code in which the error occurs is returned to the client.

It is also possible to use URL redirects for error processing:

You can also use URL redirect error handling.

Error_page 403 http://example.com/forbidden.html;error_page 404 = 301http://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).

In this case, by default, the response code 302 is returned to the client. It can only be changed to a redirect status code (301, 302, 303, 307, and 308).

These directives are inherited from the previous level if and only if there are no error_page directives defined on the current level.

Only if no error_page directive is defined at the current level, the error_page information will be inherited from the previous level.

Try_filesSyntax: 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:

Checks the existence of the specified sequence file and uses the first found file for processing, which is performed in the current context. Build the file path from the file parameters according to the root and alias instructions. You can check to see if the directory exists, requiring a post / for example, "$uri/". If the file is not found, it is internally redirected to the uri specified in the last parameter. For example:

Location / p_w_picpaths/ {try_files $uri / pendant picturePicpathsUniverse default.gif;} location = / p_w_picpaths/default.gif {expires 30s;} III. Define the relevant configuration of the client request: keepalive_timeoutSyntax: keepalive_timeout timeout [header_timeout]; Default: keepalive_timeout 75sscape 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.

The first field sets the delay for the persistent connection client to open the server, and the 0 value disables the persistent connection. The second field sets the "Keep-Alive: timeout=time" time value in the HEAD field. The two fields can be different.

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 and Konqueror browsers recognize the "Keep-Alive: timeout=time" value in the HEADER header field. MSIE automatically shuts down after 60 seconds of persistent connection.

Keepalive_requestsSyntax: keepalive_requests number;Default: keepalive_requests 100; context: http, server, locationThis 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.

Sets the maximum value of the requested persistent connection. Once the maximum value is exceeded, the connection is closed.

Keepalive_disableSyntax: 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.

Disable the persistent connection feature when accessing a browser that is not suitable. Browser indicates which browser is affected. The msie6 value indicates that the persistent connection feature is disabled once an older version of the MSIE browser POST request is received. The safari value indicates that Safari on the operating system of the macOS and macOS classes and browsers like Safari disable the persistent connection feature. The none value indicates that all browsers have the long connection feature enabled.

Send_timeoutSyntax: send_timeout time;Default: send_timeout 60sbot 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.

Sets a timeout for sending a response message to the client. The timeout is only between two write operations and does not apply to all responses. If the client does not accept it at this time, the connection is closed.

Client_body_buffer_sizeSyntax: client_body_buffer_size size;Default: client_body_buffer_size 8k | 16kscape 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.

Set the read client request body to set the buffer size, in case the request body is larger than the buffer, the entire body or part of the body is written to a temporary file. By default, the buffer size is equal to two memory pages, and 8K for 32-bit systems and 16K for 64-bit systems.

Client_body_temp_pathSyntax: 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

Defines the directory used to store temporary files for the client request body. A subdirectory hierarchy of up to 3 levels can be used under a specified directory. For example, in the following configuration

Client_body_temp_path / spool/nginx/client_temp 1 2

A path to a temporary file might look like this:

A temporary file may have a root similar to the following file:

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

Client_body_temp_path / var/tmp/client_body 2 1 1

1: indicates that the first-level subdirectory is represented by a hexadecimal number; 0murf

2: indicates that the secondary subdirectory is represented by a 2-digit 16-process number: 00-ff

3: indicates that the three-level subdirectory is represented by a 2-digit 16-process number: 00-ff

4. Configuration related to client restriction: limit_rateSyntax: 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.

Limit the response rate transmitted to the client. The rate is specified in bytes per second. A value of 0 indicates no limit. The limit is set on a per-request basis, and if a client opens two connections at the same time, the total limit is twice the specified limit.

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:

The speed limit can also be set in the $limit_rate variable. It may be useful when restrictions need to be based on certain situations:

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.

The speed limit can also be set in the "X-Accel-Limit-Rate" HEARER field in the proxy server response. You can disable this feature using the proxy_ignore_header, fastcgi_ignore_header, uwsgi_ignore_header, and scgi_ignore_header directives.

Limit_exceptSyntax: 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:

Restrict the access to a location by allowed HTTP methods. This method field can be one of GET, HEAD, POST, PUT, DELETE, MKCOL, COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, LOCK, UNLOCK, PATCH. Allowing the GET method also makes the HEAD method available. Instructions in the ngx_http_access_module and ngx_http_auth_basic_module modules are required to allow other methods.

Limit_except GET {allow 192.168.1.0 Universe 32; deny all;}

Please note that this will limit access to all methods except GET and HEAD.

Note: this will restrict all methods except GET and HEAD.

5. AioSyntax: aio on | off | threads [= pool]; Default: aio off;Context: http, server, locationThis directive appeared in version 0.8.11.

Enables or disables the use of asynchronous file I take O (AIO) on FreeBSD and Linux:

Enable or disable asynchronous file I _ Universe O on FreeBSD and Linux systems

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:

On FreeBSD, AIO is supported after FreeBSD 4.3. Prior to FreeBSD 11.0, AIO could be statically linked to the kernel.

Options VFS_AIO

Or dynamically load into a kernel module

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:

On Linux systems, AIO is supported after Linux2.6.22, and directio must also be enabled, otherwise reads will be blocked.

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.

On Linux systems, directio can only be used to read 512K-aligned blocks (4K for XFS file systems). The unaligned end of the file is in blocking mode when read. For byte range requests and FLV requests, the same applies to the beginning of the file: reading misaligned data at the beginning and end of the file will be blocked.

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.

When both AIO and sendfile are enabled on Linux systems, the AIO scope is greater than or equal to the file size specified by the directio directive. Sendfile is used when it is smaller than the file size specified in the directio instruction, or when directio is disabled.

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:

Finally, files can be read and sent without being blocked by a worker process, using multithreaded mode

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:

Read and send file operations are unloaded to the thread of the specified pool. If the name of the pool is omitted, the pool will use the name "default". The pool name can also be set with a variable

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.

By default, multithreading is disabled and can be enabled using the-- with-threads control field. In general, multithreading is only compatible with epoll, kqueue, and eventport methods. Only Linux systems support multithreading to send files.

DirectioSyntax: directio size | off;Default: directio off;Context: http, server, locationThis 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:

Enable O_DIRECT tags (FreeBSD, Linux), F_NOCACHE tags (macOS), or the directio () function (Solaris) when the read file is larger than the specified block. This directive automatically disables (0.7.15) sendfile's use of a given request. Use when sending large files:

Directio 4m

Or when using aio on Linux.

Or use aio on Linux systems.

Open_file_cacheSyntax: 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:

Configure a cache that can store the following information:

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 descriptors, their size and modification time

Directory information that exists

File query errors, such as "file not found", "no read permission", etc. (error caching needs to be enabled separately from open_file_cache_errors. )

The directive has the following parameters:

The instruction has the following fields

Max

Sets the maximum number of elements in the cache; on cache overflow the least recently used (LRU) elements are removed

Sets the maximum number of elements in the cache and uses the LRU algorithm when overflowing.

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

Defines a period of time during which an element is removed from the cache if it is not accessed. By default, the duration is 60 seconds.

Off

Disables the cache

Disable caching

Example:

For example

Open_file_cache max=1000 inactive=20s;open_file_cache_valid 30s: opening of fileholders cachets errors on;open_file_cache_errorsSyntax: 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.

Enables or disables file viewing errors in open_file_cache.

Open_file_cache_min_usesSyntax: 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.

Sets the minimum access value for files during the inactive configuration in open_file_cache, requiring that the file descriptor be kept open in the cache.

Open_file_cache_validSyntax: open_file_cache_valid time;Default: open_file_cache_valid 60sbot context: http, server, location

Sets a time after which open_file_cache elements should be validated.

Sets the time interval for checking the validity of cached items.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report