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 (3)-- http Protocol Module configuration

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

Share

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

Detailed explanation of common configuration of Nginx (3) ngx_http_access_module module

Example Configuration

Sample configuration

Location / {deny 192.168.1.1; allow 192.168.1.0 all;Default 24; allow 10.1.1.0 Compact 16; allow 2001 Velcro DB8 Groupe 32; deny all;} allowSyntax: allow address | unix: | all;Default:-Context: http, server, location, limit_except

Allows access for the specified network or address. If the special value unix: is specified (1.5.1), allows access for all UNIX-domain sockets.

Allows access to the specified network or address if there is a unix:, in the value that allows access to all UNIX-domain sockets.

DenySyntax: deny address | CIDR | unix: | all;Default:-Context: http, server, location, limit_except

Denies access for the specified network or address. If the special value unix: is specified (1.5.1), denies access for all UNIX-domain sockets.

Block the specified network and address if there is a unix:, in the value to block all UNIX-domain socket access.

Ngx_http_auth_basic_module

Implement user-based access control and use basic mechanism for user authentication

Example Configuration

Sample configuration

Location / {auth_basic "closed site"; auth_basic_user_file conf/htpasswd;} auth_basicSyntax: auth_basic string | off;Default: auth_basic off;Context: http, server, location, limit_except

Enables validation of user name and password using the "HTTP Basic Authentication" protocol. The specified parameter is used as a realm. Parameter value can contain variables (1.3.10,1.2.7). The special value off allows cancelling the effect of the auth_basic directive inherited from the previous configuration level.

Auth_basic_user_fileSyntax: auth_basic_user_file file;Default:-Context: http, server, location, limit_except

Specifies a file that keeps user names and passwords, in the following format:

Indicates a file with the user name and password saved in the following format:

# commentname1:password1name2:password2:commentname3:password3

The file name can contain variables.

File names can use variables.

The following password types are supported:

Password types support the following categories:

Encrypted with the crypt () function; can be generated using the "htpasswd" utility from the Apache HTTP Server distribution or the "openssl passwd" command

Hashed with the Apache variant of the MD5-based password algorithm (apr1); can be generated with the same tools

Specified by the "{scheme} data" syntax (1.0.3 +) as described in RFC 2307; currently implemented schemes include PLAIN (an example one, should not be used), SHA (1.3.13) (plain SHA-1 hashing, should not be used) and SSHA (salted SHA-1 hashing, used by some software packages, notably OpenLDAP and Dovecot).

Using the crypt () function encryption, you can generate it using htpasswd in Apache HTTP Server or use the openssl passwd command.

The Apache variable hash of md5's cryptographic algorithm (apr1) can be generated using the same tool

Specifying "{scheme} data" as described in RFC 2307, currently implemented scenarios include: PLAIN (an example that should not be used), SHA (1.3.13) (normal SHA-1 hash, which should not be used), and SSHA (salt SHA-1 hash in some packages, especially OpenLDAP and Dovecot).

Support for SHA scheme was added only to aid in migration from other web servers. It should not be used for new passwords, since unsalted SHA-1 hashing that it employs is vulnerable to rainbow table attacks.

Support for the SHA scenario only adds help in migrating from other web servers. It should not be used for new passwords because the unsalted sha-1 hash it uses is vulnerable to rainbow table***.

Ngx_http_stub_status_module

Used to output basic status information of nginx

Example Configuration

Sample configuration

Location / basic_status {stub_status;}

This configuration creates a simple web page with basic status data which may look like as follows

This configuration creates a simple page to display the basic data status, with the following effect

Active connections: 291 server accepts handled requests 16630948 16630948 31070465 Reading: 6 Writing: 179 Waiting: 106stub_statusSyntax: stub_status;Default:-Context: server, location

The basic status information will be accessible from the surrounding location.

Read basic status information from a nearby location.

Data (data segment of information)

Active connections

The current number of active client connections including Waiting connections.

The actual number of active connections to the client, including waiting for connections.

Accepts

The total number of accepted client connections.

Total number of connections to the client.

Handled

The total number of handled connections. Generally, the parameter value is the same as accepts unless some resource limits have been reached (for example, the worker_connections limit).

The total number of connections completed. Typically, the value of this field is the same as the total number of connections, unless some reach the resource limit. (for example, worker_connections restrictions)

Requests

The total number of client requests.

Total number of clients requested.

Reading

The current number of connections where nginx is reading the request header.

Nginx reads the actual number of request headers.

Writing

The current number of connections where nginx is writing the response back to the client.

The actual number of response messages returned by nginx to the client

Waiting

The current number of idle client connections waiting for a request.

The actual number of clients waiting to request a connection

Ngx_http_log_module

Ngx_http_log_module module logs in the specified format

Example Configuration

Sample configuration

Log_format basic'$remote_addr [$time_local]'$protocol $status $bytes_sent $bytes_received''$session_time';access_log / spool/logs/nginx-access.log basic buffer=32k;access_log

Sets the path, format, and configuration for a buffered log write. Several logs can be specified on the same level. Logging to syslog can be configured by specifying the "syslog:" prefix in the first parameter. The special value off cancels all access_log directives on the current level.

Set the path, format, and log buffer configuration. Multiple logs can be configured at one level. Recording to syslog requires the addition of "syslog:" in the first field. The special value off cancels all access log instructions at the current level.

If either the buffer or gzip parameter is used, writes to log will be buffered.

The buffer size must not exceed the size of an atomic write to a disk file. For FreeBSD this size is unlimited.

When buffering is enabled, the data will be written to the file:

If the next log line does not fit into the buffer;if the buffered data is older than specified by the flush parameter;when a worker process is re-opening log files or is shutting down.

If the gzip parameter is used, then the buffered data will be compressed before writing to the file. The compression level can be set between 1 (fastest, less compression) and 9 (slowest, best compression). By default, the buffer size is equal to 64K bytes, and the compression level is set to 1. Since the data is compressed in atomic blocks, the log file can be decompressed or read by "zcat" at any time.

If the gzip field is enabled, the buffered data is compressed before being written to the file. The compression level can be set from 1 (fastest, lowest compression ratio) to 9 (slowest, highest compression ratio). The default buffer size is 64K and the compression level is 1. Because the data is compressed into atomic block, log files can be unzipped or read through zcat.

Example:

For example

Access_log / path/to/log.gz basic gzip flush=5m

For gzip compression to work, nginx must be built with the zlib library.

In order for gzip compression to work, nginx must be installed with the zlib library.

The file path can contain variables, but such logs have some constraints:

The file path can be a variable, but such logs are limited.

The user whose credentials are used by worker processes should have permissions to create files in a directory with such logs

Buffered writes do not work

The file is opened and closed for each log write. However, since the descriptors of frequently used files can be stored in a cache, writing to the old file can continue during the time specified by the open_log_file_cache directive's valid parameter

-

Users of the worker process should have permission to create files in the directory of such logs.

Buffered writes will not work

Open and close the file every time the file is written. However, because the descriptors of frequently used files can be stored in the cache, the files can be written continuously at the time specified by open_log_file_cache.

The if parameter enables conditional logging. A session will not be logged if the condition evaluates to "0" or an empty string.

If parameter conditional is enabled in the log, and paintings with a condition of 0 or an empty string in if will not be logged.

Log_formatSyntax: log_format name [escape=default | json] string...; Default:-Context: stream

Specifies the log format, for example:

Indicates the file log format, such as

Log_format proxy'$remote_addr [$time_local]'$protocol $status $bytes_sent $bytes_received'$session_time "$upstream_addr"'"$upstream_bytes_sent"$upstream_bytes_received"$upstream_connect_time"'

The escape parameter (1.11.8) allows setting json or default characters escaping in variables, by default, default escaping is used.

The escape field allows you to set the conversion of json or default characters to variables, and default character conversion is enabled by default.

Open_log_file_cacheSyntax: open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time]; open_log_file_cache off;Default: open_log_file_cache off;Context: stream, server

Defines a cache that stores the file descriptors of frequently used logs whose names contain variables. The directive has the following parameters:

Define a cache to store file descriptors for commonly used logs whose names contain variables:

The directive has the following parameters:

Contains the following instructions:

Max

Sets the maximum number of descriptors in a cache; if the cache becomes full the least recently used (LRU) descriptors are closed

Set the maximum cache value, and when the cache is full, turn off the descriptor using the LRU algorithm.

Inactive

Sets the time after which the cached descriptor is closed if there were no access during this time; by default, 10 seconds

Sets the time when the cached descriptor is turned off when there is no access during this period; by default it is 10 seconds

Min_uses

Sets the minimum number of file uses during the time defined by the inactive parameter to let the descriptor stay open ina cache; by default, 1

Set the minimum number of file usage within the time defined by the inactive parameter to keep the descriptor open in the cache; by default it is 1

Valid

Sets the time after which it should be checked that the file still exists with the same name; by default, 60 seconds

Set the time to check, the file still exists under the same name; by default it is 60 seconds

Off

Disables caching

Turn off caching

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.

The ngx_http_gzip_module module is a filter that compresses the response with the "gzip" method. This usually helps to reduce the size of the transmitted data by half or more.

Example Configuration

Sample configuration

Gzip on;gzip_min_length 1000 × gzipkeeper proxied expired no-cache no-store private auth;gzip_types text/plain application/xml;gzipSyntax: gzip on | off;Default: gzip off;Context: http, server, location, if in location

Enables or disables gzipping of responses.

Enables or disables gzipping responses.

Gzip_buffersSyntax: gzip_buffers number size;Default: gzip_buffers 324k | 168k context: http, server, location

Sets the number and size of buffers used to compress a response. By default, the buffer size is equal to one memory page. This is either 4K or 8K, depending on a platform.

Set the corresponding number and size of compressed buffers. The default buffer size is equal to one memory page. According to the platform is 4k or 8k.

Until version 0.7.28, four 4K or 8K buffers were used by default.

Prior to 0.7.28, quantity 4, size 4K and 8K were the default.

Gzip_comp_levelSyntax: gzip_comp_level level;Default: gzip_comp_level 1; context: http, server, location

Sets a gzip compression level of a response. Acceptable values are in the range from 1 to 9.

Sets the gzip compression level of response messages. The accepted value is from 1 to 9.

Gzip_disableSyntax: gzip_disable regex...; Default:-Context: http, server, locationThis directive appeared in version 0.6.23.

Disables gzipping of responses for requests with "User-Agent" header fields matching any of the specified regular expressions.

Disables the gzipping response when the "User-Agent" HEADER field matches the specified regular expression.

The special mask "msie6" (0.7.12) corresponds to the regular expression "MSIE [4-6].", but works faster. Starting from version 0.8.11, "MSIE 6.0;... SV1" is excluded from this mask.

The special matching code "msie6" is equivalent to "MSIE [4-6]." but it runs faster. After 0.8.11, "MSIE 6.0;... SV1" is excluded from this mask.

Gzip_min_lengthSyntax: gzip_min_length length;Default: gzip_min_length 20 th context: http, server, location

Sets the minimum length of a response that will be gzipped. The length is determined only from the "Content-Length" response header field.

Sets the minimum length of the compressed response. This length only responds to the HEARD field based on "Content-Length".

Gzip_http_versionSyntax: gzip_http_version 1.0 | 1.1 gzip_http_version default: http, server, location

Sets the minimum HTTP version of a request required to compress a response.

Set the minimum HTTP version of the compressed message.

Gzip_proxiedSyntax: gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any...; Default: gzip_proxied off;Context: http, server, location

Enables or disables gzipping of responses for proxied requests depending on the request and response. The fact that the request is proxied is determined by the presence of the "Via" request header field. The directive accepts multiple parameters:

Enables or disables gzipping responses for proxy requests, depending on the request and response. The fact that the request is proxied is determined by the existence of the "Via" request header field. This entry accepts multiple fields:

Off

Disables compression for all proxied requests, ignoring other parameters

All proxy requests disable compression and reject other fields.

Expired

Enables compression if a response header includes the "Expires" field with a value that disables caching

If the response header contains the "Expires" field and has a value that disables caching, compression is enabled

No-cache

Enables compression if a response header includes the "Cache-Control" field with the "no-cache" parameter

Compression is enabled if the response header contains a "Cache-Control" field with the "no-cache" parameter

No-store

Enables compression if a response header includes the "Cache-Control" field with the "no-store" parameter

Compression is enabled if the response header contains the "Cache-Control" field of the "no-store" parameter

Private

Enables compression if a response header includes the "Cache-Control" field with the "private" parameter

Compression is enabled if the response header contains a "Cache-Control" field with the "private" parameter

No_last_modified

Enables compression if a response header does not include the "Last-Modified" field

Enable compression if the response header does not contain the "Last-Modified" field

No_etag

Enables compression if a response header does not include the "ETag" field

Enable compression if the response header does not contain the "ETag" field

Auth

Enables compression if a request header includes the "Authorization" field

Enable compression if the request header contains the "Authorization" field

Any

Enables compression for all proxied requests.

Provides compression for all proxied requests.

Gzip_typesSyntax: gzip_types mime-type...; Default: gzip_types text/html;Context: http, server, location

Enables gzipping of responses for the specified MIME types in addition to "text/html". The special value "*" matches any MIME type (0.8.29). Responses with the "text/html" type are always compressed.

In addition to "text / html", gzipping is allowed for the specified MIME type. The special value "×" matches any MIME type (0.8.29). Responses to the "text / html" type are always compressed.

Gzip_varySyntax: gzip_vary on | off;Default: gzip_vary off;Context: http, server, location

Enables or disables inserting the "Vary: Accept-Encoding" response header field if the directives gzip, gzip_static, or gunzip are active.

If the instruction gzip, gzip_static, or gunzip is active, enable or disable the insertion of the "Vary: Accept-Encoding" response header field.

Ngx_http_ssl_module

The ngx_http_ssl_module module provides the necessary support for HTTPS.

Example Configuration

Sample configuration

To reduce the processor load it is recommended to

In order to reduce the processor load, configuration is recommended.

Set the number of worker processes equal to the number of processors

Enable keep-alive connections

Enable the shared session cache

Disable the built-in session cache

And possibly increase the session lifetime (by default, 5 minutes):

Set the number of worker processes equal to the number of processors

Enable long connection

Enable shared session caching

Disable built-in session caching

May increase the lifecycle of the session (default 5 minutes)

Worker_processes auto;http {... Server {listen 443 ssl; keepalive_timeout 70; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers AES128-SHA:AES256-SHA:RC4-SHA:DES-CBC3-SHA:RC4-MD5; ssl_certificate / usr/local/nginx/conf/cert.pem; ssl_certificate_key / usr/local/nginx/conf/cert.key Ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m;...} sslSyntax: ssl on | off;Default: ssl off;Context: http, server

Enables the HTTPS protocol for the given virtual server.

Enable HTTPS in the virtual host

It is recommended to use the ssl parameter of the listen directive instead of this directive.

It is recommended that you use the ssl parameter of the listen instruction instead of this directive.

Ssl_buffer_sizeSyntax: ssl_buffer_size size;Default: ssl_buffer_size 16kscape context: http, serverThis directive appeared in version 1.5.9.

Sets the size of the buffer used for sending data.

Sets the buffer size of the sent data.

By default, the buffer size is 16k, which corresponds to minimal overhead when sending big responses. To minimize Time To First Byte it may be beneficial to use smaller values, for example:

The default buffer size is 16K, which is equivalent to minimum overhead when sending a large response. To minimize Time To First Byte, you can use a smaller value, such as:

Ssl_buffer_size 4kssloping certificate Syntax: ssl_certificate file;Default:-Context: http, server

Specifies a file with the certificate in the PEM format for the given virtual server. If intermediate certificates should be specified in addition to a primary certificate, they should be specified in the same file in the following order: the primary certificate comes first, then the intermediate certificates. A secret key in the PEM format may be placed in the same file.

Specifies the file in PEM format for a given virtual server. If you want to specify intermediate certificates in addition to the primary certificate, you should specify them in the same file in the following order: first the primary certificate, then the intermediate certificate. Secret keys in PEM format can be placed in the same file.

Since version 1.11.0, this directive can be specified multiple times to load certificates of different types, for example, RSA and ECDSA:

Due to version 1.11.0, this directive can be specified multiple times to load different types of certificates, such as RSA and ECDSA:

Server {listen 443 ssl; server_name example.com; ssl_certificate example.com.rsa.crt; ssl_certificate_key example.com.rsa.key; ssl_certificate example.com.ecdsa.crt; ssl_certificate_key example.com.ecdsa.key;...}

Only OpenSSL 1.0.2 or higher supports separate certificate chains for different certificates. With older versions, only one certificate chain can be used.

Only OpenSSL 1.0.2 or later supports separate certificate chains to obtain different certificates. When using an older version, only one certificate chain can be used.

It should be kept in mind that due to the HTTPS protocol limitations virtual servers should listen on different IP addresses:

It should be remembered that due to HTTPS protocol restrictions, virtual servers should listen on different IP addresses:

Server {listen 192.168.1.1 server 443; server_name one.example.com; ssl_certificate one.example.com.crt;...} server {listen 192.168.1.2 VR 443; server_name two.example.com; ssl_certificate two.example.com.crt;...}

Otherwise the first server's certificate will be issued for the second site.

Otherwise, the certificate of the first server will be published to the second site.

Ssl_certificate_keySyntax: ssl_certificate_key file;Default:-Context: http, server

Specifies a file with the secret key in the PEM format for the given virtual server.

Specifies the private key file in PEM format for a given virtual server.

Ssl_ciphers # very useful configuration item Syntax: ssl_ciphers ciphers;Default: ssl_ciphers Higg _ Vol _ null _ L _ http _ context: http, server

Specifies the enabled ciphers. The ciphers are specified in the format understood by the OpenSSL library, for example:

Specifies that ciphertext is enabled. The ciphertext is indicated as a format understood by the OpenSSL library, such as:

Ssl_ciphers all rig aNULLV exp. EXPORT56 RC4 RSArig HIGHV.

The full list can be viewed using the "openssl ciphers" command.

The entire list can be viewed by the "openssl ciphers" command.

The previous versions of nginx used different ciphers by default.

Previous versions of nginx encryption do not understand by default.

Ssl_client_certificate # very useful configuration item Syntax: ssl_client_certificate file;Default:-Context: http, server

Specifies a file with trusted CA certificates in the PEM format used to verify client certificates and OCSP responses if ssl_stapling is enabled.

If ssl_stapling is enabled, define a file that uses a trusted CA certificate in PEM format to validate the client certificate and OCSP response.

The list of certificates will be sent to clients. If this is not desired, the ssl_trusted_certificate directive can be used.

The list of certificates will be sent to the customer. If not, you can use the ssl_trusted_certificate directive.

Ssl_protocolsSyntax: ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2] [TLSv1.3]; Default: ssl_protocols TLSv1 TLSv1.1 TLSv1.2;Context: http, server

Enables the specified protocols.

Enable the specified protocol

The TLSv1.1 and TLSv1.2 parameters (1.1.13,1.0.12) work only when OpenSSL 1.0.1 or higher is used.

TLSv1.1 (1.1.13) and TLSv1.2 (1.0.12) only work above the OpenSSL1.0.1 level used.

The TLSv1.3 parameter (1.13.0) works only when OpenSSL 1.1.1 built with TLSv1.3 support is used.

TLSv1.3 (1.13.0) only works above the OpenSSL1.1.1 level used.

Ssl_session_cacheSyntax: ssl_session_cache off | none | [builtin [: size]] [shared:name:size]; Default: ssl_session_cache none;Context: http, server

Sets the types and sizes of caches that store session parameters. A cache can be of any of the following types:

Sets the type and size of the save session field cache file. Caching can be configured as follows

Off

The use of a session cache is strictly prohibited: nginx explicitly tells a client that sessions may not be reused.

Completely disable session caching: nginx explicitly indicates that client sessions cannot be reused

None

The use of a session cache is gently disallowed: nginx tells a client that sessions may be reused, but does not actually store session parameters in the cache.

Session caching is not allowed: nginx tells the client that the session may be reused, but does not actually store session parameters in the cache.

Builtin

A cache built in OpenSSL; used by one worker process only. The cache size is specified in sessions. If size is not given, it is equal to 20480 sessions. Use of the built-in cache can cause memory fragmentation.

OpenSSL built-in cache. Can only be used for one worker process. The cache size is indicated by the session. If no size is given, the default is 20480 sessions. Using a built-in cache can cause memory fragmentation

Shared

A cache shared between all worker processes. The cache size is specified in bytes; one megabyte can store about 4000 sessions. Each shared cache should have an arbitrary name. A cache with the same name can be used in several virtual servers.

Caching between all worker processes. The cache size is indicated by bytes that a megabyte can store about 4000 sessions. Each shared cache should have any name. Caches with the same name can be used in multiple virtual servers.

Both cache types can be used simultaneously, for example:

All caches can be used at the same time, such as

Ssl_session_cache builtin:1000 shared:SSL:10m

But using only shared cache without the built-in cache should be more efficient.

However, using only the shared cache, it should be more efficient to turn off the built-in cache.

Ssl_session_timeoutSyntax: ssl_session_timeout time;Default: ssl_session_timeout 5mscape context: http, server

Specifies a time during which a client may reuse the session parameters.

Specifies the timeout for which a client can reuse session parameters.

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.

The ngx_http_rewrite_module module is used to change the request URI using perl regular expressions, return redirection, and conditionally select the configuration.

The ngx_http_rewrite_module module directives are processed in the following order:

The ngx_http_rewrite_module module instructions work on the following principles:

The directives of this module specified on the server level are executed sequentially

Repeatedly:

A location is searched based on a request URI

The directives of this module specified inside the found location are executed sequentially

The loop is repeated if a request URI was rewritten, but not more than 10 times.

-

The module instructions at all levels of the virtual host are executed sequentially.

Repeatability

Request URI to query a location.

The module instructions are executed sequentially in location.

If the URI is rewritten to continue the above action, but not more than 10 times.

RewriteSyntax: rewrite regex replacement [flag]; Default:-Context: server, location, if

If the specified regular expression matches a request URI, URI is changed as specified in the replacement string. The rewrite directives are executed sequentially in order of their appearance in the configuration file. It is possible to terminate further processing of the directives using flags. If a replacement string starts with "http://"," https://", or "$scheme", the processing stops and the redirect is returned to a client.

If a request URI matches the specified regular expression, the URI will change based on the specified replacement. Rewrite instructions are executed in the order in which they appear in the configuration file. You can use flags to terminate further instructions. If the replacement field starts with "http://"," https://", or "$scheme", the processing terminates and the redirection is returned to the client.

An optional flag parameter can be one of:

A flag option can be one of the following

Last

Stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI

Stop processing the current ngx_http_rewrite_module instruction set and start searching for new locations that match the changed URI

Break

Stops processing the current set of ngx_http_rewrite_module directives as with the break directive

Stop processing the current ngx_http_rewrite_module instruction set, similar to break instructions.

Redirect

Returns a temporary redirect with the 302 code; used if a replacement string does not start with "http://"," https://", or "$scheme"

Returns temporary redirection, using 302 status codes. Replacement cannot start with "http://"," https://", "$scheme".

Permanent

Returns a permanent redirect with the 301 code.

Return to permanent redirection, using status code 301.

The full redirect URL is formed according to the request scheme ($scheme) and the server_name_in_redirect and port_in_redirect directives.

URL all redirects according to the scheme ($scheme) in the request message and the instructions in server_name_in_redirect and port_in_redirect.

Example:

For example:

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

But if these directives are put inside the "/ download/" location, the last flag should be replaced by break, or otherwise nginx will make 10 cycles and return the 500 error:

But if these fields are put into the "/ download/" location, the ending flag must be replaced with break, otherwise the nginx will loop 10 times and return a 500 error status code.

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

If a replacement string includes the new request arguments, the previous request arguments are appended after them. If this is undesired, putting a question mark at the end of a replacement string avoids having them appended, for example:

If the replacement field includes the new request parameters, the old request parameters will be appended. If you don't want to do this, suffix it in replacement? To avoid attaching old request parameters For example

Rewrite ^ / users/ (. *) $/ show?user=$1? Last

If a regular expression includes the "}" or ";" characters, the whole expressions should be enclosed in single or double quotes.

If a regular expression contains "}" or ";", the entire expression should be enclosed in single or double quotation marks.

ReturnSyntax: return code [text]; return code URL; return URL;Default:-Context: server, location, if

Stops processing and returns the specified code to a client. The non-standard code 444 closes a connection without sending a response header.

Stop processing and return the status code to the client. Non-standard status code 444, do not send response header, directly close the connection.

Starting from version 0.8.42, it is possible to specify either a redirect URL (for codes 301,302,303,307, and 308) or the response body text (for other codes). A response body text and redirect URL can contain variables. As a special case, a redirect URL can be specified as a URI local to this server, in which case the full redirect URL is formed according to the request scheme ($scheme) and the server_name_in_redirect and port_in_redirect directives.

Starting with version 0.8.42, you can specify the redirect URL (for status codes 301,302,303,307, and 308) or the response body text (other codes). The response body text can use variables. As a special case, the redirect URL can be specified as the server's URI, in which case the full redirect URL is generated based on the request scheme ($scheme) and the server_name_in_redirect and port_in_redirect instructions.

In addition, a URL for temporary redirect with the code 302 can be specified as the sole parameter. Such a parameter should start with the "http://"," https://", or "$scheme" string. A URL can contain variables.

In addition, 302 is a temporary redirect unique status code. You can use http://", "https://"," $scheme "as the beginning of a field, and URL can use variables.

Only the following codes could be returned before version 0.7.51: 204,400,402-406,408,410,411,413,416, and 500504.

The following code can only be returned before version 0.7.51: 204, 400, 402-406, 408, 410, 411, 413, 416, and 500-504.

The code 307 was not treated as a redirect until versions 1.1.16 and 1.0.13.

307 status codes are not supported before versions 1.1.16 and 1.0.13

The code 308 was not treated as a redirect until version 1.13.0.

308 status codes are not supported before version 1.13.0

IfSyntax: if (condition) {...} Default:-Context: server, location

The specified condition is evaluated. If true, this module directives specified inside the braces are executed, and the request is assigned the configuration inside the if directive. Configurations inside the if directives are inherited from the previous configuration level.

The specified condition will be evaluated. If true, the contents of the curly braces in the module will be executed and the request will be assigned to the if instruction. The configuration in the if directive inherits from the previous configuration level.

A condition may be any of the following:

The conditions can be as follows:

A variable name; false if the value of a variable is an empty string or "0"

Before version 1.0.1, any string starting with "0" was considered a false value.

Comparison of a variable with a string using the "=" and "! =" operators "

Matching of a variable against a regular expression using the "(for case-sensitive matching) and" (for case-insensitive matching) operators. Regular expressions can contain captures that are made available for later reuse in the $1... 9 variables. Negative operators "! ~" and "! ~ ×" are also available. If a regular expression includes the "}" or ";" characters, the whole expressions should be enclosed in single or double quotes.

Checking of a file existence with the "- f" and "!-f" operators

Checking of a directory existence with the "- d" and "!-d" operators

Checking of a file, directory, or symbolic link existence with the "- e" and "!-e" operators

Checking for an executable file with the "- x" and "!-x" operators.

one

A variable name, false if the variable value is an empty string or 0

Prior to version 1.0.1, any string that began with 0 was considered false

Compare strings can use the "=" and "! =" symbols.

Variable matching regular expressions use "~" for case-sensitive matching and "~ ×" for case-insensitive matching. Regular expressions can be captured later using $1.. reference 9. Anti-matching "!"! "can also be used. If "}" appears in the middle of the regular expression; "the entire character needs to be enclosed in single or double quotation marks.

Check the existence of files using the "- f"!-f "field

Check the existence of the directory using the "- d"!-d "field

Check the existence of files, directories, and symbolic links using the "- e"!-e "field

Check the executable file using the "- x"- x" field

Examples:

For example

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

A value of the $invalid_referer embedded variable is set by the valid_referers directive.

The value of the variable $invalid_referer is set by the valid_referers instruction.

SetSyntax: set $variable value;Default:-Context: server, location, if

Sets a value for the specified variable. The value can contain text, variables, and their combination.

Sets the value of the specified variable. Values can be text and variables, or text-combined variables.

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. It should be kept in mind that fabricating a request with an appropriate "Referer" field value is quite easy, and so the intended purpose of this module is not to block such requests thoroughly but to block the mass flow of requests sent by regular browsers. It should also be taken into consideration that regular browsers may not send the "Referer" field even for valid requests.

The The ngx_http_referer module is used to prevent certain requests from accessing the site, and the request header "Referer" value is not valid. It should be remembered that it is quite easy to make a request with the appropriate "referrer" field values, so the purpose of this module is not to block these requests completely, but to prevent the large number of requests sent by regular browsers. It should also be considered that ordinary browsers may not send "Referer" fields, even for valid requests.

Example Configuration

Sample configuration

Valid_referers none blocked server_names * .example.com example.* www.example.org/galleries/ ~\ .Google\; if ($invalid_referer) {return 403;} valid_referersSyntax: valid_referers none | blocked | server_names | string...; Default:-Context: server, location

Specifies the "Referer" request header field values that will cause the embedded $invalid_referer variable to be set to an empty string. Otherwise, the variable will be set to "1". Search for a match is case-insensitive.

Indicates that the "Referer" value of the request header will make the built-in variable $invalid_ referer value an empty string. Otherwise, the variable is set to 1. Search matches are not case sensitive.

Parameters can be as follows:

The parameters are as follows:

None

The "Referer" field is missing in the request header

There is no "Referer" field in the request header

Blocked

The "Referer" field is present in the request header, but its value has been deleted by a firewall or proxy server; such values are strings that do not start with "http://" or" https://";

The request header has a "Referer" field but is deleted by the firewall or proxy. These values and strings do not start with "http://""https://"."

Server_names

The "Referer" request header field contains one of the server names

The "Referer" field in the request header contains the name of a virtual host

Arbitrary string wildcard

Defines a server name and an optional URI prefix. A server name can have an "×" at the beginning or end. During the checking, the server's port in the "Referer" field is ignored

Define a server name and an optional URI prefix. The server name can have "x" at the beginning or end. The server port in the "Referer" field is ignored during the check

Regular expression regular expression

The first symbol should be a "~" It should be noted that an expression will be matched against the text starting after the "http://" or" https://".

The first symbol should be "~". It should be noted that after "http://" or "https://", the expression will match the text.

Example:

For example

Valid_referers none blocked server_names * .example.com example.* www.example.org/galleries/ ~\ .Google.

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