Nginx常用配置详解(三)——http协议模块配置
Nginx常用配置详解(三)
ngx_http_access_module模块
Example Configuration
配置样例
location / { deny 192.168.1.1; allow 192.168.1.0/24; allow 10.1.1.0/16; allow 2001:0db8::/32; deny all;}
allow
Syntax: allow address | CIDR | 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.
允许指明的网络或地址接入,如果值中有unix:
,允许所有UNIX-domain套接字接入。
deny
Syntax: 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.
阻止指明的网络和地址,如果值中有unix:
,阻止所有UNIX-domain套接字接入。
ngx_http_auth_basic_module
实现基于用户的访问控制,使用basic机制进行用户认证;
Example Configuration
配置样例
location / { auth_basic "closed site"; auth_basic_user_file conf/htpasswd;}
auth_basic
Syntax: 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_file
Syntax: 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:
指明一个保存了用户名称及密码的文件文件,如下格式:
# commentname1:password1name2:password2:commentname3:password3
The file name can contain variables.
文件名可以使用变量。
The following password types are supported:
密码类型支持如下种类:
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).
使用crypt()函数加密,可以使用Apache HTTP Server中的htpasswd生成或者使用
openssl passwd
命令。md5的密码算法(apr1)的Apache变量hash,可以使用相同的工具生成;
像RFC 2307描述的语法一样指明"{scheme}data",目前实现的方案包括:PLAIN(一个示例,不应该使用)、SHA(1.3.13)(普通的SHA - 1哈希,不应该使用)和SSHA(在一些软件包中使加盐SHA - 1哈希,特别是OpenLDAP和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.
对SHA方案的支持只增加了从其他web服务器迁移的帮助。它不应该被用于新密码,因为它使用的不加盐的sha - 1哈希很容易受到rainbow table***。
ngx_http_stub_status_module
用于输出nginx的基本状态信息
Example Configuration
配置样例
location /basic_status { stub_status;}
This configuration creates a simple web page with basic status data which may look like as follows
该配置创建简单的页面用来显示基本数据状态,效果如下
Active connections: 291 server accepts handled requests 16630948 16630948 31070465 Reading: 6 Writing: 179 Waiting: 106
stub_status
Syntax: stub_status;Default: -Context: server, location
The basic status information will be accessible from the surrounding location.
从附近的location读取基本状态信息。
Data(信息的数据段)
Active connections
The current number of active client connections including Waiting connections.
客户端的实际活动连接数,包括等待连接。
accepts
The total number of accepted client connections.
客户端的总连接数。
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).
完成的连接总数。通常的这个字段的值与总连接数相同,除非一些达到资源限制。(例如worker_connections
限制)
requests
The total number of client requests.
请求的客户端总数。
Reading
The current number of connections where nginx is reading the request header.
nginx读取请求头部的实际数量。
Writing
The current number of connections where nginx is writing the response back to the client.
nginx返回给客户端响应报文的实际数量
Waiting
The current number of idle client connections waiting for a request.
等待请求连接的客户端的实际数量
ngx_http_log_module
ngx_http_log_module module用指明的格式记录日志
Example 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.
设定路径、格式、日志缓冲区配置。多个日志可以配置在一个级别。记录到syslog需要在第一个字段增加"syslog:"。特殊值off取消了当前级别上的所有访问日志指令。
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.
如果gzip字段启用,缓冲的数据在写入文件之前会被压缩。压缩级别可以设置从1(最快、压缩率最低)至9(最慢、压缩率最高)。默认的缓冲大小为64K,压缩级别为1.因为数据被压缩成为atomic block,日志文件可以被解压,或通过zcat读取。
Example:
例如
access_log /path/to/log.gz basic gzip flush=5m;
For gzip compression to work, nginx must be built with the zlib library.
为保证gzip压缩工作,nginx必须同 zlib 库一同安装。
The file path can contain variables, but such logs have some constraints:
文件路径可以是变量,但这样的日志有一定的限制。
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
-worker进程的用户应该在这样日志的目录中有创建文件的权限。
缓冲写入将不能工作
每次文件写入都要打开关闭文件。但是,由于经常使用的文件的描述符可以存储在缓存中,可以在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参数条件式,if中条件之为0
或者为空字符串的绘画将不被记录日志。
log_format
Syntax: log_format name [escape=default|json] string ...;Default: -Context: stream
Specifies the log format, for example:
指明文件日志格式,例如
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.
escape字段允许设置json或default字符转换成变量,默认情况下,default字符转换被启用。
open_log_file_cache
Syntax: 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:
定义一个缓存,用于存储常用日志的文件描述符,这些日志的名称包含变量:
The directive has the following parameters:
包含如下指令:
max
sets the maximum number of descriptors in a cache; if the cache becomes full the least recently used (LRU) descriptors are closed
设定缓存最大值,缓存满后,使用LRU算法关闭描述符。
inactive
sets the time after which the cached descriptor is closed if there were no access during this time; by default, 10 seconds
设置在这段时间内没有访问时缓存的描述符关闭的时间;默认情况下是10秒
min_uses
sets the minimum number of file uses during the time defined by the inactive parameter to let the descriptor stay open in a cache; by default, 1
在inactive参数定义的时间内设置最小的文件使用数量,让描述符在缓存中保持开放;默认情况下是1
valid
sets the time after which it should be checked that the file still exists with the same name; by default, 60 seconds
设置需要检查的时间,该文件仍然以相同的名称存在;默认情况下是60秒
off
disables 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.
ngx_http_gzip_module模块是一个用"gzip"方法压缩响应的过滤器。这通常有助于将传输数据的大小减少一半甚至更多。
Example Configuration
配置样例
gzip on;gzip_min_length 1000;gzip_proxied expired no-cache no-store private auth;gzip_types text/plain application/xml;
gzip
Syntax: gzip on | off;Default: gzip off;Context: http, server, location, if in location
Enables or disables gzipping of responses.
启用或禁用gzipping响应。
gzip_buffers
Syntax: gzip_buffers number size;Default: gzip_buffers 32 4k|16 8k;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.
设定相应压缩缓冲区数量和大小。默认缓冲大小等于一内存分页。根据平台为4k或8k。
Until version 0.7.28, four 4K or 8K buffers were used by default.
0.7.28之前,数量4 大小4K和8K是默认情况。
gzip_comp_level
Syntax: 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.
设定响应报文gzip压缩等级。接收值从1到9。
gzip_disable
Syntax: 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.
"User-Agent" HEADER字段匹配到指定的正则表达式时禁用gzipping响应。
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.
特殊的匹配码"msie6",相当于"MSIE [4-6].",但是运行速度更快。0.8.11后,"MSIE 6.0;…SV1"被排除在这个掩码之外。
gzip_min_length
Syntax: gzip_min_length length;Default: gzip_min_length 20;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.
设定压缩响应的最小长度。这个长度只根据 "Content-Length"响应HEARD字段。
gzip_http_version
Syntax: gzip_http_version 1.0 | 1.1;Default: gzip_http_version 1.1;Context: http, server, location
Sets the minimum HTTP version of a request required to compress a response.
设定压缩报文的最低HTTP版本。
gzip_proxied
Syntax: 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:
根据请求和响应,启用或禁用代理请求的gzipping响应。请求被代理的事实是由"Via"请求头字段的存在决定的。该条目接受多个字段:
off
disables compression for all proxied requests, ignoring other parameters;
所有代理请求禁用压缩,拒绝其他字段。
expired
enables compression if a response header includes the "Expires" field with a value that disables caching;
如果响应头包含"Expires"字段,并具有禁用缓存的值,则启用压缩;
no-cache
enables compression if a response header includes the "Cache-Control" field with the "no-cache" parameter;
如果响应头包含带有"no-cache"参数的"Cache-Control"字段,则启用压缩;
no-store
enables compression if a response header includes the "Cache-Control" field with the "no-store" parameter;
如果响应头包含"no-store"参数的"Cache-Control"字段,则启用压缩;
private
enables compression if a response header includes the "Cache-Control" field with the "private" parameter;
如果响应头包含带有"private"参数的"Cache-Control"字段,则启用压缩;
no_last_modified
enables compression if a response header does not include the "Last-Modified" field;
如果响应标头不包含"Last-Modified"字段,则启用压缩;
no_etag
enables compression if a response header does not include the "ETag" field;
如果响应头不包含"ETag"字段,则启用压缩;
auth
enables compression if a request header includes the "Authorization" field;
如果请求头包含"Authorization"字段,则启用压缩;
any
enables compression for all proxied requests.
为所有的proxied请求提供压缩。
gzip_types
Syntax: 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.
除了"文本/ html"之外,还允许对指定的MIME类型进行gzipping。特殊值"×"匹配任何MIME类型(0.8.29)。对"文本/ html"类型的响应总是被压缩。
gzip_vary
Syntax: 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.
如果指令gzip、gzip_static或gunzip是活动的,则启用或禁用插入"Vary: Accept-Encoding"响应头字段。
ngx_http_ssl_module
ngx_http_ssl_module模块为HTTPS提供了必要的支持。
Example Configuration
配置样例
To reduce the processor load it is recommended to
为了减少处理器负载,建议配置。
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):
设置与处理器数量相等的工作进程数
启用长连接
启用共享会话缓存
禁用内置会话缓存
可能增加会话的生命周期(默认 5分钟)
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; ... }
ssl
Syntax: ssl on | off;Default: ssl off;Context: http, server
Enables the HTTPS protocol for the given virtual server.
虚拟主机中启用HTTPS
It is recommended to use the ssl parameter of the listen directive instead of this directive.
建议使用listen指令的ssl参数而不是这个指令。
ssl_buffer_size
Syntax: ssl_buffer_size size;Default: ssl_buffer_size 16k;Context: http, serverThis directive appeared in version 1.5.9.
Sets the size of the buffer used for sending 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:
默认缓冲大小16K,当发送大的响应时,这相当于最小的开销,为了将最小化Time To First Byte,可以使用较小的值,例如:
ssl_buffer_size 4k;
ssl_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.
指定给定虚拟服务器的PEM格式的文件。如果要在主证书之外指定中间证书,则应按照以下顺序在同一文件中指定它们:首先是主证书,然后是中间证书。PEM格式的秘密密钥可以放在同一个文件中。
Since version 1.11.0, this directive can be specified multiple times to load certificates of different types, for example, RSA and ECDSA:
由于版本1.11.0,这个指令可以多次指定,以加载不同类型的证书,例如RSA和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.
只有OpenSSL 1.0.2或更高版本支持单独的证书链,以获得不同的证书。使用旧版本时,只能使用一个证书链。
It should be kept in mind that due to the HTTPS protocol limitations virtual servers should listen on different IP addresses:
应该记住,由于HTTPS协议限制,虚拟服务器应该监听不同的IP地址:
server { listen 192.168.1.1:443; server_name one.example.com; ssl_certificate one.example.com.crt; ...}server { listen 192.168.1.2: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.
否则,第一个服务器的证书将被发布到第二个站点.
ssl_certificate_key
Syntax: ssl_certificate_key file;Default: -Context: http, server
Specifies a file with the secret key in the PEM format for the given virtual server.
指定给定虚拟服务器的PEM格式的私钥文件。
ssl_ciphers ####非常用配置项
Syntax: ssl_ciphers ciphers;Default: ssl_ciphers HIGH:!aNULL:!MD5;Context: http, server
Specifies the enabled ciphers. The ciphers are specified in the format understood by the OpenSSL library, for example:
指定启用密文。密文被指明为OpenSSL库理解的格式,例如:
ssl_ciphers ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
The full list can be viewed using the "openssl ciphers" command.
整个列表可以被"openssl ciphers"命令查看。
The previous versions of nginx used different ciphers by default.
之前版本的nginx加密方式默认不懂。
ssl_client_certificate ####非常用配置项
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.
如果启用ssl_stapling,定义一个文件使用PEM格式的可信CA证书验证客户端证书和OCSP响应。
The list of certificates will be sent to clients. If this is not desired, the ssl_trusted_certificate directive can be used.
证书列表将被发送给客户。如果不需要,可以使用ssl_trusted_certificate指令。
ssl_protocols
Syntax: 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.
启用指明的协议
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)和TLSv1.2(1.0.12)只工作在使用的OpenSSL1.0.1级别以上时。
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)只工作在使用的OpenSSL1.1.1级别以上时。
ssl_session_cache
Syntax: 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:
设定存储会话字段缓存文件的类型和大小。缓存可以使用如下配置
off
the use of a session cache is strictly prohibited: nginx explicitly tells a client that sessions may not be reused.
完全禁止会话缓存:nginx明确指明客户端会话不能重用
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.
不允许使用会话缓存:nginx告诉客户端会话可能重用,但实际上并没有在缓存中存储会话参数。
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内置的缓存。只能用于一个worker进程。缓存大小由会话指明。如果没有给出大小,默认为20480会话。使用内置缓存可以引起内存碎片
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.
在所有worker进程之间的缓存。缓存大小用bytes指明,一个兆字节可以存储大约4000个会话。每个共享缓存应该具有任意名称。具有相同名称的缓存可以在多个虚拟服务器中使用。
Both cache types can be used simultaneously, for example:
所有缓存可同时使用,例如
ssl_session_cache builtin:1000 shared:SSL:10m;
but using only shared cache without the built-in cache should be more efficient.
但是只使用共享缓存,关闭内置缓存应该更高效。
ssl_session_timeout
Syntax: ssl_session_timeout time;Default: ssl_session_timeout 5m;Context: http, server
Specifies a time during which a client may reuse the 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.
ngx_http_rewrite_module模块用于使用perl正则表达式改变请求URI,返回重定向,有条件地选择配置。
The ngx_http_rewrite_module module directives are processed in the following order:
ngx_http_rewrite_module模块指令工作于一下原则:
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.
-
在虚拟主机各层级上的该模块指令按顺序执行。
重复性
请求URI查询一个location。
该模块指令在location中顺序执行。
如果URI被重写持续上面的动作,但不超过10次。
rewrite
Syntax: 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.
如果一个请求URI匹配了指明的正则表达式,URI将会根据指明的replacement
做出改变。重写指令按他们在配置文件中出现的次序顺序执行。可以使用flags
终止更远的指令运行。如果replacement
字段中以 "http://", "https://", 或 "$scheme"开头,处理终止,返回重定向给客户端。
An optional flag parameter can be one of:
一个flag
选项可以是如下之一
last
stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI;
停止处理当前的ngx_http_rewrite_module指令集,并开始搜索匹配更改的URI的新位置;
break
stops processing the current set of ngx_http_rewrite_module directives as with the break directive;
停止处理当前的ngx_http_rewrite_module指令集,类似break指令。
redirect
returns a temporary redirect with the 302 code; used if a replacement string does not start with "http://", "https://", or "$scheme";
返回临时重定向,使用302状态码,replacement
不能以"http://", "https://", "$scheme"开头。
permanent
returns a permanent redirect with the 301 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全部重定向根据请求报文中的scheme($scheme)和server_name_in_redirect、port_in_redirect中的指令。
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:
但是这些字段如果放进"/download/"location中,结尾flag必须替换成为break,否则nginx将会循环10次然后返回500错误状态码。
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:
如果replacement
字段包括新的请求参数,旧的请求参数将会附在后面。如果不希望这样做,在replacement
中后缀?,避免旧请求参数附加。例如
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.
如果一个正则表达式包含"}"或者";",整个表达式应该用单引号或双引号括起来。
return
Syntax: 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.
停止处理,并给客户端返回状态码。非标准状态码444,不发送响应头部,直接关闭连接。
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.
从0.8.42版本开始,可以指定重定向URL(用于状态码301、302、303、307和308)或响应主体text
(其他代码)。响应主体text
可以使用变量。作为特例,可以将重定向URL指定为该服务器的URI,在这种情况下,完全重定向URL根据请求方案($scheme)和server_name_in_redirect和port_in_redirect指令来生成。
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.
此外,302是临时重定向唯一状态码。可以使用http://", "https://", "$scheme"作为字段的开头,URL
可以使用变量。
Only the following codes could be returned before version 0.7.51: 204, 400, 402 - 406, 408, 410, 411, 413, 416, and 500 - 504.
以下代码只可以在0.7.51版本之前返回:204、400、402 - 406、408、410、411、413、416和500 - 504。The code 307 was not treated as a redirect until versions 1.1.16 and 1.0.13.
版本1.1.16和1.0.13之前不支持307状态码The code 308 was not treated as a redirect until version 1.13.0.
1.13.0版本之前不支持308状态码
if
Syntax: 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.
指明的condition
将被评估。如果为真,该模块中的大括号中的内容将会被执行,请求被分配到if指令中。if指令中的配置从上一个配置级别继承。
A condition may be any of the following:
条件可以是如下情况:
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.
1
一个变量名,如果变量值是一个空串或0,则为false
1.0.1版本前,任何以0开头的的字符串被认为是false
比较字符串可以使用"="和"!="符号。
变量匹配正则表达式使用"~"区分大小写匹配,"~×"不区分大小匹配。正则表达式可以在之后使用
$1..$9
引用捕获。取反匹配"!~""!~×"也可以使用。如果正则表达式中间出现"}"";"整个字符需要用单引号或双引号括起来。检查文件存在性使用"-f""!-f" 字段
检查目录存在性使用"-d" "!-d"字段
检查文件、目录、符号链接的存在性使用"-e""!-e"字段
检查文件的可执行使用"-x""-x"字段
Examples:
例如
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.
变量$invalid_referer
的值由valid_referers指令设定。
set
Syntax: set $variable value;Default: -Context: server, location, if
Sets a value for the specified variable. The value can contain text, variables, and their combination.
设定指明变量的值。值可以是文本和变量,也可是文本结合变量。
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 ngx_http_referer模块被用于阻止某些请求接入网站,这些情求报文头部"Referer"值无效。应该记住,使用适当的"引用器"字段值来制造一个请求是相当容易的,因此这个模块的目的不是要彻底阻塞这些请求,而是阻止常规浏览器发送的大量请求。还应该考虑到,普通的浏览器可能不会发送"Referer"字段,即使是对有效的请求。
Example Configuration
配置样例
valid_referers none blocked server_names *.example.com example.* www.example.org/galleries/ ~\.google\.;if ($invalid_referer) { return 403;}
valid_referers
Syntax: 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.
指明请求报文头部的"Referer"值将使内置的变量$invalid_referer值为空字符串。否则,变量会被设置成为1。搜索匹配不区分大小写。
Parameters can be as follows:
参数如下所示:
none
the "Referer" field is missing in the request header;
请求头部中没有"Referer"字段
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://";
请求头部中有"Referer"字段但是被防火墙或者代理删除,这些值和字符串不以"http://""https://"开头。
server_names
the "Referer" request header field contains one of the server names;
请求头部中有"Referer"字段包含一个虚拟主机的名称
arbitrary string通配符
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;
定义一个服务器名称和一个可选的URI前缀。服务器名在开始或结束时可以有"×"。在检查期间,"Referer"字段中的服务器端口被忽略;
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://".
第一个符号应该是"~"。应该注意,在 "http:// "或"https:// "之后,表达式将与文本匹配。
Example:
例如
valid_referers none blocked server_names *.example.com example.* www.example.org/galleries/ ~\.google\.;