FAQ

Page Discussion Edit History

NginxHttpCoreModuleJa

「HTTP Core モジュール」原文のコピーです。これから訳していきます。

Contents

[edit] 概要

Nginx の HTTP プロセスのコア機能をコントロールします。

[edit] ディレクティブ

[edit] aio

シンタックス: aio [on|off|sendfile]

デフォルト: off

コンテキスト: http, server, location

このディレクティブは Linux カーネル 2.6.1922 から使えます。Linux では directio を使う必要があり、sendfile サポートは自動的に無効にされます。

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

FreeBSD 5.2.1 以前、Nginx 0.8.12 では sendfile を必ず無効にする必要があります。

location /video {
    aio on; 
    sendfile off;
    output_buffers 1 128k;
}

FreeBSD 5.2.1 と Nginx 0.8.12 では sendfile とともに使用できます。

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

[edit] alias

シンタックス: alias file-path|directory-path

デフォルト: no

コンテキスト: location

このディレクティブは指示されたロケーションへのリクエストを提供するための基盤として使われるパスを指定します。 root ディレクティブに似ていますが、ドキュメントルートは変更するわけではなく、たんにリクエストに使われるファイスシステムのパスです。リクエストのロケーション部分は Nginx が発行するリクエストではドロップされます。実際にどのようになっているのか、次の例を見てみましょう。

location  /i/ {
  alias  /spool/w3/images/;
}

"/i/top.gif" へのリクエストは Nginx に "/spool/w3/images/top.gif" のファイルを提供するように指示します。ご覧のように location のうしろの URI の部分だけが追加されます。location そのもの、ここでは "/i/" はドロップされます。root ではフルが追加されてしまいます。例えば上の例では "/spool/w3/images/i/top.gif" となり、location "/i/" 含まれてしまいます。

alias は正規表現によって指定された location でも使用できます。

例えば、

location ~ ^/download/(.*)$ {
  alias /home/website/files/$1;
}

"/download/book.pdf" のリクエストは "/home/website/files/book.pdf" のファイルを返します。繰り返しますが、 alias で定義されたパスに追加されるのは location のうしろのリクエスト URI だけです。alias.

置き換えられるパスに変数を使うのことは可能です。

[edit] chunked_transfer_encoding

シンタックス: chunked_transfer_encoding on|off

デフォルト: on

コンテキスト: http, server, location

このディレクティブ (0.7.66以上) はレスポンスでのチャンク化されたエンコーディングを有効にします (HTTP 1.1 以上を使用した接続でのみ有効です)。

[edit] client_body_in_file_only

シンタックス: client_body_in_file_only on|off

デフォルト: off

コンテキスト: http, server, location

このディレクティブは nginx にクライアントのリクエストボディを一時ディスクファイルに強制的に保存させます。たとえそのボディのサイズが0だとしても保存されます。

このディレクティブが有効の場合、リクエスト完了時にこのファイルは削除されないので注意してください。

このディレクティブはデバッギングと埋め込み Perl モジュール$r->request_body_file で使用できます。

[edit] client_body_in_single_buffer

シンタックス: client_body_in_single_buffer

デフォルト: off

コンテキスト: http, server, location

このディレクティブ (0.7.58以上) は単一のクライアントリクエストバッファにボディ全体を保持するかどうかを指定します。コピーの工程を削減するために変数 $request_body を使用するときには、このディレクティブを勧めます。

リクエストボディが単一バッファ (client_body_buffer_size を参照)では保持できないときでも、そのボディはディスクに書きこまれます。

[edit] client_body_buffer_size

シンタックス: client_body_buffer_size the_size

デフォルト: 8k/16k

コンテキスト: http, server, location

このディレクティブはクライアントリクエストボディのバッファサイズを指定します。

リクエストボディがこのバッファよりも大きい時はリクエストボディ全体もしくは一部が一時ファイルに書きこまれます。

デフォルトのサイズは 2 ページ分のサイズと同じで、これはプラットフォームによりますが 8K もしくは 16K です。

[edit] client_body_temp_path

シンタックス: client_body_temp_path dir-path [ level1 [ level2 [ level3 ]

デフォルト: client_body_temp

コンテキスト: http, server, location

このディレクティブはリクエストのボディとともに一時ファイルをを保存するためのディレクトリを指定します。

dir-path にてサブディレクトリの階層を三階層まで設定可能です。

client_body_temp_path  /spool/nginx/client_temp 1 2;

ディレクトリ構造は次のようになります:

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

[edit] client_body_timeout

シンタックス: client_body_timeout time

デフォルト: 60

コンテキスト: http, server, location

このディレクティブはクライアントからのボディリクエストの読み出しタイムアウトを設定します。

このタイムアウトは一度のリードステップでボディが得られないときのみ設定されます。もしこの時間後にクライアントが何も送信しなければ nginx は "Request time out" (408) のエラーを返します。

[edit] client_header_buffer_size

シンタックス: client_header_buffer_size size

デフォルト: 1k

コンテキスト: http, server

このディレクティブはクライアントからのリクエストヘッダー用のヘッダーバッファサイズを設定します。

リクエストのほとんど大多数では 1K のバッファサイズで十分なはずです。

しかし、リクエストヘッダーに大きな cookie がある場合や WAP クライアントからのリクエストの場合は、ヘッダーは 1K に収まらないかもしれません。したがって、リクエストヘッダーやリクエストヘッダー行はこのバッファ内に完全には収まらないので nginx はより大きなバッファを割り当てます。このより大きなバッファのサイズは large_client_header_buffers で設定できます。

[edit] client_header_timeout

シンタックス: client_header_timeout time

デフォルト: 60

コンテキスト: http, server

クライアントのリクエストのタイトル読み出しのタイムアウトを設定します。

このタイムアウトは一度のリードステップでヘッダーが得られないときのみ設定されます。もしこの時間後にクライアントが何も送信しなければ nginx は "Request time out" (408) のエラーを返します。

[edit] client_max_body_size

シンタックス: client_max_body_size size

デフォルト: client_max_body_size 1m

コンテキスト: http, server, location

このディレクティブはクライアントリクエストの受信ボディサイズの最大値を設定します。これはリクエストのヘッダーにある Content-Length の行で指示されています。

もしサイズが設定値より大きいとクライアントには "Request Entity Too Large" (413) エラーが送られます。

ブラウザはこのエラーを正しく表示する方法を知らないことに留意してください。

[edit] default_type

シンタックス: default_type MIME-type

デフォルト: default_type text/plain

コンテキスト: http, server, location

標準 MIME マップが何も指定されていないファイルに使われるデフォルト MIME タイプを指定します。

typesも参照してください。

[edit] directio

シンタックス: directio [size|off]

デフォルト: directio off

コンテキスト: http, server, location

このディレクティブは規定よりも大きいサイズのファイルを読むための O_DIRECT (FreeBSD, Linux)、F_NOCACHE (Mac OS X) もしくは directio() 関数 (Solaris) のフラグの利用を有効にします。このディレクティブはこのリクエスト用の sendfile の利用を無効にします。大きなファイルに便利かもしれません:

    directio  4m;

[edit] error_page

シンタックス: error_page code [ code... ] [ = | =answer-code ] uri | @named_location

デフォルト: no

コンテキスト: http, server, location, if in location

このディレクティブはエラーが発生したときに表示される URI を指定します。

例:

error_page   404          /404.html;
error_page   502 503 504  /50x.html;
error_page   403          http://example.com/forbidden.html;
error_page   404          = @fetch;

さらに、アンサーコードを別のものに変更することも可能です。例えば:

error_page 404 =200 /.empty.gif;

もしプロキシサーバや FastCGI サーバによって誤ったアンサーが処理されてこのサーバが別のアンサーコード、例えば 200、302、401、404 を返すことがある場合、返されるコードを発行することができます:

error_page   404  =  /404.php;

リダイレクションの間に URI を変更する必要がない場合、エラーページの処理を名前をつけた location にリダイレクトさせることができます:

location / (
    error_page 404 = @fallback;
)
 
location @fallback (
    proxy_pass http://backend;
)

[edit] if_modified_since

シンタックス: if_modified_since [off|exact|before]

デフォルト: if_modified_since exact

コンテキスト: http, server, location

このディレクティブ (0.7.24) はファイル修正時刻とリクエストヘッダー "If-Modified-Since" の時刻の比較方法を定義します:

  • off — "If-Modified-Since" リクエストヘッダーをチェックしない (0.7.34);
  • exact — 完全一致;
  • before — ファイル修正時刻は "If-Modified-Since" リクエストヘッダーの時刻より前でなくてはならない

[edit] internal

シンタックス: internal

デフォルト: no

コンテキスト: location

internal が、location のマッチがいわゆる "internal(内部)" のリクエストのみ使われるのかどうかを示します。

外部のリクエストに大してはエラー "Not found" (404) を返します。

内部リクエストは次のものです:

  • error_pageでの指示によるリダイレクトされたリクエスト
  • "ngx_http_ssi_module" モジュールのコマンド include virtual によって作成されたサブリクエスト
  • "ngx_http_rewrite_module" モジュールの rewrite 指示によって変更されたリクエスト

クライアントがエラーページを直接取得するのを防ぐ例です:

error_page 404 /404.html;
location  /404.html {
  internal;
}

[edit] keepalive_timeout

シンタックス: keepalive_timeout [ time ]

デフォルト: keepalive_timeout 75

コンテキスト: http, server, location

最初のパラメータはクライアントとのキープアライブ接続のタイムアウトを指定します。サーバはこの時間後に接続を閉じます。

二番目の任意のパラメータはレスポンスのヘッダー Keep-Alive: timeout=timetime 値を指定します。このヘッダーによりブラウザによっては接続を閉じさせることができ、サーバが閉じる必要はなくなります。このパラメータなしでは nginx は Keep-Alive ヘッダーを送りません (とはいえ、これは接続を "キープアライブ" させておくものではありません)。

このパラメータはそれぞれ異なります。

ブラウザが Keep-Alive ヘッダーをどのように扱うかについて:

  • MSIE と Opera は "Keep-Alive: timeout=<N>" ヘッダーを無視します。
  • MSIE は接続を約 60-65 秒間保ち、その後 TCP RST を送信します。
  • Opera は長時間接続を保ちます。
  • Mozilla は N プラス約 1-10 秒間接続を保ちます。
  • Konqueror は約 N 秒間接続を保ちます。

[edit] keepalive_requests

シンタックス: keepalive_requests n

デフォルト: keepalive_requests 100

コンテキスト: http, server, location

キープアライブ接続越しにリクエストできる数。

[edit] large_client_header_buffers

シンタックス: large_client_header_buffers number size

デフォルト: large_client_header_buffers 4 4k/8k

コンテキスト: http, server

クライアントリクエストから大きなヘッダーを読むためのバッファの最大数と最大サイズを指定します。

リクエスト行はひとつのバッファのサイズよりも小さくなくてはなりません。もしクライアントがそれよりも大きいヘッダーを送ると、nginx はエラー "Request URI too large" (414) を返します。

リクエストの最長のヘッダー行もひとつのバッファのサイズ以下である必要があります。さもなければクライアントはエラー "Bad request" (400) を受け取ります。

バッファは必要時のみ分離されます。

デフォルトでは、ひとつのバッファのサイズはページのサイズと同等で、プラットフォームによりますが、4K もしくは 8K です。ワーキングリクエストの終了時に接続が変わりキープアライブが提示された場合、これらのバッファは解放されます。

[edit] limit_except

シンタックス: limit_except methods {...}

デフォルト: no

コンテキスト: location

このディレクティブは location 内へのアクセス可能な HTTP-methods を制限します。

制限には ngx_http_access_module と ngx_http_auth_basic_module モジュールのディレクティブが使えます:

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

[edit] limit_rate

シンタックス: limit_rate speed

デフォルト: no

コンテキスト: http, server, location, if in location

このディレクティブはクライアントへの返信伝送速度を指定します。速度は秒あたりのバイト数で指定します。制限が有効なのはひとつの接続だけです。つまり、もしクライアントが2つの接続を開いている場合、トータルの速度はこの制限設定の2倍以上になります。

何かの条件をもとにしてサーバレベルでクライアントの速度を制限する必要がある場合は、このディレクティブは当てはまりません。代わりに、以下のように $limit_rate の変数に値を指定して制限を設定してください:

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

また、 X-Accel-Limit-Rate ヘッダー (XSendfile) を設定することにより proxy_pass レスポンス (HttpProxyModule) によって返される個々のレスポンスのレートをコントロールすることもできます。これは X-Accel-Redirect ヘッダー無しで可能です。

[edit] limit_rate_after

シンタックス: limit_rate_after time

デフォルト: limit_rate_after 1m

コンテキスト: http, server, location, if in location

このディレクティブは最初の部分が送信された後でのみ、スピードを制限します。

[edit] listen

syntax: listen address:port [ default(deprecated) | default_server | [ backlog=num | rcvbuf=size | sndbuf=size | accept_filter=filter | deferred | bind | ipv6only=[on|off] | ssl ] ]

default: listen 80

context: server

The listen directive specifies the address and port accepted by the enclosing server {...} block. It is possible to specify only an address, only a port, or a server name as the address.

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

IPv6 address(0.7.36) are set in square brackets:

listen [::]:8000; 
listen [fe80::1];

In Linux by default any IPv6 TCP socket also accepts IPv4 traffic using the IPv4 to IPv6 mapped address format, i.e., ::ffff:<IPv4 adddress in dotted decimal notation>. E.g., ::ffff:192.168.0.27 maps the IPv4 address 192.168.0.27 to an IPv6 address.

When you enable the address [::]:80, binding port 80 using IPv6, in the listen directive, in Linux, by default, the IPv4 port 80 is also enabled. Meaning that nginx listens for both IPv4 and IPv6 incoming traffic. Therefore if you erroneously specify also a IPv4 address you'll get an already bind address error when reloading nginx configuration.

In Linux the separation of the IPv6 and IPv4 stacks is controlled through the runtime parameter: net.ipv6.bindv6only which has the value 0 by default.

If you want to use separate sockets for IPv4 and IPv6 you should set this parameter to 1 using sysctl.

Note that any nginx instance that was running before you made the change will continue to accept IPv4 traffic. Therefore you should edit your nginx configuration to reflect the new setup for IPv6 and IPv4 packet handling and do a restart.

If on the other hand you launched another server instance (vhost) and you expect it to also handle IPv4 traffic by using only, for example:

listen [::]:80;

the binding of the IPv4 address will fail. The correct way to to this is by using the "ipv6only=on" option in the IPv6 listen directive and also specifying a IPv4 listen directive in the respective server block.

This re-editing of the configuration must be done after you changed your kernel runtime parameter. This is the most generic situation in that case (separation of IPv6 and IPv4 sockets):

listen [::]:80 ipv6only=on; # listen for IPv6 only traffic on IPv6 sockets
listen 80; # listen also for IPv4 traffic on "regular" IPv4 sockets

In FreeBSD the default is separate IPv4 and IPv6 sockets. Therefore "listen [::]:80" only binds port 80 for listening to IPv6 traffic. It's always necessary to specify also IPv4 listen directives if you wish to also handle IPv4 traffic.

It's possible to specify only IPv6 addresses in the listen directive. Using the "default_server ipv6only=on" option. Specific IPv6 addresses can be used with a IPv6 only default directive. Other server directives can also specifiy listen directives with IPv4 addresses. The uniqueness of the IPv6 handling concerns only the same server {...} block.

listen [2a02:750:5::123]:80;
listen [::]:80 default_server ipv6only=on;

If only the address is given, the default port nginx binds to is 80.

If the directive has the default_server parameter, then the enclosing server {...} block will be the default server for the address:port pair. This is useful for name-based virtual hosting where you wish to specify the default server block for hostnames that do not match any server_name directives. If there are no directives with the default parameter, then the default server will be the first server block in which the address:port pair appears.

The listen directive accepts several parameters, specific to the system calls listen(2) and bind(2). These parameters must follow the default parameter.

backlog=num -- is assigned parameter backlog in call listen(2). By default backlog equals -1.

rcvbuf=size -- assigned to the parameter SO_RCVBUF for the listening socket.

sndbuf=size -- assigned to the parameter SO_SNDBUF for the listening socket.

accept_filter=filter -- is assigned name accept-filter.

. It works only to FreeBSD, it is possible to use two filters -- dataready and httpready. On the signal -HUP accept-filter it is possible to change only in the quite last versions FreeBSD: 6.0, 5.4-STABLE and 4.11-STABLE.

deferred -- indicates to use that postponed accept(2) on Linux with

. the aid of option TCP_DEFER_ACCEPT.

bind -- indicates that it is necessary to make bind(2) separately

. for this pair of address:port. The fact is that if are described several directives listen with the identical port, but by different addresses and one of the directives listen listens to on all addresses for this port (*:port), then nginx will make bind(2) only to *:port. It is necessary to consider that in this case for determining the address, on which the connections arrive, is done the system call getsockname(). But if are used parameters backlog, rcvbuf, sndbuf, accept_filter or deferred, then it is always done separately for this pair of address:port bind(2).

ssl -- parameter (0.7.14) not related to listen(2) and bind(2) syscalls

. but instead specifies that connections accepted on this port should work in SSL mode. This allows to specify compact configurations for servers working with both HTTP and HTTPS. For example:
listen  80;
listen  443 default_server ssl;

Example of the use of the parameters:

listen  127.0.0.1 default_server accept_filter=dataready backlog=1024;

Since version 0.8.21 nginx is able to listen on unix sockets:

listen unix:/tmp/nginx1.sock;

[edit] location

syntax: location [=|~|~*|^~|@] /uri/ { ... }

default: no

context: server

This directive allows different configurations depending on the URI. It can be configured using both literal strings and regular expressions. To use regular expressions, you must use a prefix:

  1. "~" for case sensitive matching
  2. "~*" for case insensitive matching

To determine which location directive matches a particular query, the literal strings are checked first. Literal strings match the beginning portion of the query - the most specific match will be used. Afterwards, regular expressions are checked in the order defined in the configuration file. The first regular expression to match the query will stop the search. If no regular expression matches are found, the result from the literal string search is used.

For case insensitive operating systems, like Mac OS X or Windows with Cygwin, literal string matching is done in a case insensitive way (0.7.7). However, comparison is limited to single-byte locale's only.

Regular expression may contain captures (0.7.40), which can then be used in other directives.

It is possible to disable regular expression checks after literal string matching by using "^~" prefix. If the most specific match literal location has this prefix: regular expressions aren't checked.

By using the "=" prefix we define the exact match between request URI and location. When matched search stops immediately. E.g., if the request "/" occurs frequently, using "location = /" will speed up processing of this request a bit as search will stop after first comparison.

On exact match with literal location without "=" or "^~" prefixes search is also immediately terminated.

To summarize, the order in which directives are checked is as follows:

  1. Directives with the "=" prefix that match the query exactly. If found, searching stops.
  2. All remaining directives with conventional strings. If this match used the "^~" prefix, searching stops.
  3. Regular expressions, in the order they are defined in the configuration file.
  4. If #3 yielded a match, that result is used. Otherwise, the match from #2 is used.

It is important to know that nginx does the comparison against decoded URIs. For example, if you wish to match "/images/%20/test", then you must use "/images/ /test" to determine the location.

Example:

location  = / {
  # matches the query / only.
  [ configuration A ] 
}
location  / {
  # matches any query, since all queries begin with /, but regular
  # expressions and any longer conventional blocks will be
  # matched first.
  [ configuration B ] 
}
location ^~ /images/ {
  # matches any query beginning with /images/ and halts searching,
  # so regular expressions will not be checked.
  [ configuration C ] 
}
location ~* \.(gif|jpg|jpeg)$ {
  # matches any request ending in gif, jpg, or jpeg. However, all
  # requests to the /images/ directory will be handled by
  # Configuration C.   
  [ configuration D ] 
}

Example requests:

  • / -> configuration A
  • /documents/document.html -> configuration B
  • /images/1.gif -> configuration C
  • /documents/1.jpg -> configuration D

Note that you could define these 4 configurations in any order and the results would remain the same. While nested locations are allowed by the configuration file parser, their use is discouraged and may produce unexpected results.

The prefix "@" specifies a named location. Such locations are not used during normal processing of requests, they are intended only to process internally redirected requests (see error_page, try_files).

[edit] log_not_found

syntax: log_not_found [on|off]

default: log_not_found on

context: http, server, location

The directive enables or disables messages in error_log about files not found on disk.

[edit] log_subrequest

syntax: log_subrequest [on|off]

default: log_subrequest off

context: http, server, location

The directive enables or disables messages in access_log about sub-requests such as rewrite rules and/or SSI requests.

[edit] msie_padding

syntax: msie_padding [on|off]

default: msie_padding on

context: http, server, location

This directive enables or disables the the msie_padding feature for MSIE browsers, and Chrome (as of nginx 0.8.25+). When this is enabled, nginx will pad the size of the response body to a minimum of 512 bytes, for responses with a status code above or equal to 400.

The padding prevents the activation of "friendly" HTTP error pages in MSIE and Chrome, so as to not hide the more-informative error pages from the server.

[edit] msie_refresh

syntax: msie_refresh [on|off]

default: msie_refresh off

context: http, server, location

This directive allows or forbids issuing a refresh instead of doing a redirect for MSIE.

[edit] open_file_cache

syntax: open_file_cache max = N [inactive = time] | off

default: open_file_cache off

context: http, server, location

The directive sets the cache activity on. These information can be stored:

  • Open file descriptors, information with their size and modification time;
  • Information about the existence of directories;
  • Error information when searches for a file - no file, do not have rights to read, etc. See also open_file_cache_errors

Options directive:

  • max - specifies the maximum number of entries in the cache. When the cache overflows, the least recently used(LRU) items will be removed;
  • inactive - specifies the time when the cached item is removed, if it has not been downloaded during that time, the default is 60 seconds;
  • off - prohibits the cache activity.

Example:

 open_file_cache max=1000 inactive=20s; 
 open_file_cache_valid    30s; 
 open_file_cache_min_uses 2;
 open_file_cache_errors   on;

[edit] open_file_cache_errors

syntax: open_file_cache_errors on | off

default: open_file_cache_errors off

context: http, server, location

The directive specifies to cache errors or not when searching a file.

[edit] open_file_cache_min_uses

syntax: open_file_cache_min_uses number

default: open_file_cache_min_uses 1

context: http, server, location

The directive defines the minimum use number of a file within the time specified in the directive parameter inactive in open_file_cache. ?If use more than the number, the file descriptor will remain open in the cache.

[edit] open_file_cache_valid

syntax: open_file_cache_valid time

default: open_file_cache_valid 60

context: http, server, location

The directive specifies the time when need to check the validity of the information about the item in open_file_cache.

[edit] optimize_server_names

syntax: optimize_server_names [ on|off ]

default: optimize_server_names on

context: http, server

Directive activates or deactivates optimization of host name checks for name-based virtual servers.

In particular, the check influences the name of the host used in redirects. If optimization is on, and all name-based servers listening on one address:port pair have identical configuration, then names are not checked during request execution and redirects use first server name.

If redirect must use host name passed by the client, then the optimization must be turned off.

Note: this directive is deprecated in nginx 0.7.x, use server_name_in_redirect instead.

[edit] port_in_redirect

syntax: port_in_redirect [ on|off ]

default: port_in_redirect on

context: http, server, location

Directive allows or prevents port indication in redirects handled by nginx.

If port_in_redirect is off, then Nginx will not add the port in the url when the request is redirected.

[edit] post_action

syntax: post_action [ uri|off ]

default: post_action off

context: http, server, location, if-in-location

Defines a URI to sub-request upon completion of current request.

location /protected_files { 
	internal;
 
	proxy_pass http://127.0.0.2;
	post_action /protected_done;
}
 
# Send the post_action request to a FastCGI backend for logging.
location /protected_done {
	internal;
	fastcgi_pass 127.0.0.1:9000;
}

[edit] recursive_error_pages

syntax: recursive_error_pages [on|off]

default: recursive_error_pages off

context: http, server, location

recursive_error_pages enables or disables following a chain of error_page directives.

[edit] resolver

syntax: resolver address

default: no

context: http, server, location

Directive defines DNS server address, e.g.

resolver 127.0.0.1;

[edit] resolver_timeout

syntax: resolver_timeout time

default: 30s

context: http, server, location

Directive defines timeout for name resolution, e.g.

resolver_timeout 5s;

[edit] root

syntax: root path

default: root html

context: http, server, location, if in location

root specifies the document root for the requests. For example, with this configuration

location  /i/ {
  root  /spool/w3;
}

A request for "/i/top.gif" will return the file "/spool/w3/i/top.gif". You can use variables in the argument.

note: Keep in mind that the root will still append the directory to the request so that a request for "/i/top.gif" will not look in "/spool/w3/top.gif" like might happen in an Apache-like alias configuration where the location match itself is dropped. Use the alias directive to achieve the Apache-like functionality.

[edit] satisfy

syntax: satisfy [ all | any ]

default: satisfy all

context: http, server, location

version: ≥ 0.6.25

Access policy if directives from both Access module and Auth Basic module are defined in a context:

location / {
  satisfy any;
  allow 192.168.1.0/32;
  deny all;
  auth_basic "closed site";
  auth_basic_user_file conf/htpasswd;
}

[edit] satisfy_any

syntax: satisfy_any [ on | off ]

default: satisfy_any off

context: http, server, location

deprecated: 0.6.25 -- Use the satisfy directive instead

[edit] send_timeout

syntax: send_timeout the time

default: send_timeout 60

context: http, server, location

Directive assigns response timeout to client. Timeout is established not on entire transfer of answer, but only between two operations of reading, if after this time client will take nothing, then nginx is shutting down the connection.

[edit] sendfile

syntax: sendfile [ on|off ]

default: sendfile off

context: http, server, location

Directive activate or deactivate the usage of sendfile().

[edit] server

syntax: server {...}

default: no

context: http

Directive assigns configuration for the virtual server.

There is no separation of IP and name-based (the Host header of the request) servers.

Instead, the directive listen is used to describe all addresses and ports on which incoming connections can occur, and in directive server_name indicate all names of the server.

[edit] server_name

syntax: server_name name [... ]

default: server_name ""

context: server

This directive performs two actions:

  • Compares the Host header of the incoming HTTP request against the server { ... } blocks in the Nginx configuration files and selects the first one that matches. This is how virtual servers are defined. Server names are processed in the following order:
  1. full, static names
  2. names with a wildcard at the start of the name — *.example.com
  3. names with a wildcard at the end of the name — www.example.*
  4. names with regular expressions
If there is no match, a server { ... } block in the configuration file will be used based on the following order:
  1. the server block with a matching listen directive marked as [default|default_server]
  2. the first server block with a matching listen directive (or implicit listen 80;)

Example:

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

The first name becomes the basic name of server. By default the name of the machine (hostname) is used.

It is possible to use "*" for replacing the first or the last part of the name:

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

The first two of the above names (example.com and *.example.com) can be combined into one:

server {
  server_name  .example.com;
}

It is also possible to use regular expressions in server names, prepending the name with a tilde "~" like so:

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

Since nginx 0.7.12, an empty server name is supported to catch the requests without "Host" header, please note that most browsers will always send a Host header, if accessed by IP the Host header will contain the IP. To specify a catch-all block please see the default_server flag of the listen directive.

Since nginx 0.8.25 named captures can be used in server_name:

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

Some older versions of PCRE may have issues with this syntax. If any problems arise try this following syntax:

server {
  server_name   ~^(www\.)?(?P<domain>.+)$;
  root  /sites/$domain;
}

Since nginx 0.9.4, $hostname can be used as a server_name argument:

server {
  server_name $hostname;
}

[edit] server_name_in_redirect

syntax: server_name_in_redirect on|off

default: server_name_in_redirect on

context: http, server, location

If server_name_in_redirect is on, then Nginx will use the first value of the server_name directive for redirects. If server_name_in_redirect is off, then nginx will use the requested Host header.

Note: for Location headers coming from an upstream proxy (via proxy_pass for example) this may not be the only directive you need. In fact, it seems to be ignored a lot of the time. If you are seeing the upstream's server name come through and not be rewritten, you will need to use proxy_redirect to rewrite the upstream's provided hostname to what you want. Something like proxy_redirect http://some.upstream.url/ / - you will want to rewrite it to a / relative path.

[edit] server_names_hash_max_size

syntax: server_names_hash_max_size number

default: server_names_hash_max_size 512

context: http

The maximum size of the server name hash tables. For more detail see the description of tuning the hash tables in Nginx Optimizations.

[edit] server_names_hash_bucket_size

syntax: server_names_hash_bucket_size number

default: server_names_hash_bucket_size 32/64/128

context: http

Directive assigns the size of basket in the hash-tables of the names of servers. This value by default depends on the size of the line of processor cache. For more detail see the description of tuning the hash tables in Nginx Optimizations.

[edit] server_tokens

syntax: server_tokens on|off

default: server_tokens on

context: http, server, location

Whether to send the Nginx version number in error pages and Server header.

[edit] tcp_nodelay

syntax: tcp_nodelay [on|off]

default: tcp_nodelay on

context: http, server, location

This directive allows or forbids the use of the socket option TCP_NODELAY. Only included in keep-alive connections.

You can read more about the TCP_NODELAY socket option here.

[edit] tcp_nopush

syntax: tcp_nopush [on|off]

default: tcp_nopush off

context: http, server, location

This directive permits or forbids the use of the socket options TCP_NOPUSH on FreeBSD or TCP_CORK on Linux. This option is only available when using sendfile.

Setting this option causes nginx to attempt to send it's HTTP response headers in one packet on Linux and FreeBSD 4.x

You can read more about the TCP_NOPUSH and TCP_CORK socket options here.

[edit] try_files

syntax: try_files path1 [path2] uri

default: none

context: server, location

availability: 0.7.27

Checks for the existence of files in order, and returns the first file that is found. A trailing slash indicates a directory - $uri /. In the event that no file is found, an internal redirect to the last parameter is invoked. The last parameter is the fallback URI and *must* exist, or else an internal error will be raised. Unlike rewrite, $args are not automatically preserved if the fallback is not a named location. If you need args preserved, you must do so explicitly:

try_files $uri $uri/ /index.php?q=$uri&$args;

Example use in proxying Mongrel:

try_files /system/maintenance.html $uri $uri/index.html $uri.html @mongrel;
 
location @mongrel {
  proxy_pass http://mongrel;
}

Note that you can specify an HTTP status code as the last argument to try_file since Nginx version 0.7.51. Here's an example:

location / {
  try_files $uri $uri/ /error.php?c=404 =404;
}

When all other attempts to serve the content corresponding to the request fail issue a 404 Not Found.


Example of use with Drupal / FastCGI:

# for drupal 6:
try_files $uri $uri/ @drupal;
 
# for drupal 7:
try_files $uri $uri/ /index.php?q=$uri&$args;
 
# only needed for Drupal 6 (or if you absolutely need a named location)
location @drupal {
  rewrite ^ /index.php?q=$uri last; # for drupal 6
}
 
location ~ \.php$ {
  fastcgi_pass 127.0.0.1:8888;
  fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name; # if not already defined in the fastcgi_params file
  # any other specific fastcgi_params
}

In this example, the directive try_files

try_files $uri $uri/ @drupal;

Is basically the same as this:

location / {
  error_page     404 = @drupal;
  log_not_found  off;
}

Or this:

if (!-e $request_filename) {
   rewrite ^ /index.php?q=$uri last;
}

try_files is basically a replacement for the typical mod_rewrite style file/directory existence check. It is supposed to be more efficient than using if - see IfIsEvil

Examples of use with Wordpress and Joomla (typical "Front controller pattern" packages)

# wordpress (without WP Super Cache) - example 1
try_files $uri $uri/ /index.php?q=$uri&$args;
 
# wordpress (without WP Super Cache) - example 2 (it doesn't REALLY need the "q" parameter)
try_files $uri $uri/ /index.php;
 
# joomla
try_files $uri $uri/ /index.php?q=$uri&$args;
 
location ~ \.php$ {
  fastcgi_pass 127.0.0.1:8888;
  fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name; # if not already defined in the fastcgi_params file
  # any other specific fastcgi_params
}

WP Super Cache requires a bunch of static file checks. Those are not shown here.

[edit] types

syntax: types {...}

context: http, server, location

Directive assigns the correspondence of expansion and MIME-types of answers. To one MIME- type can correspond several expansions. By default it is used these correspondences:

types {
  text/html    html;
  image/gif    gif;
  image/jpeg   jpg;
}

The sufficiently complete table of mappings is included and is located in the file conf/mime.types.

So that for that determined location's for all answers would reveal MIME- type application/octet-stream, it is possible to use the following:

location /download/ {
  types         { }
  default_type  application/octet-stream;
}

[edit] underscores_in_headers

syntax: underscores_in_headers on|off

default: off

context: http, server

Allows or disallows underscores in headers.

[edit] variables_hash_bucket_size

syntax: variables_hash_bucket_size size

default: variables_hash_bucket_size 64

context: http

variables: no

phase: configuration


Assigns the key bucket size for the variables hash table.

[edit] variables_hash_max_size

syntax: variables_hash_max_size size

default: variables_hash_max_size 512

context: http

variables: no

phase: configuration


The maximum size of the variables hash table. For more detail see the description of tuning the hash tables in Nginx Optimizations.

[edit] Variables

The core module supports built-in variables, whose names correspond with the names of variables in Apache.

First of all, there are variables which represent header lines in the client request, for example, $http_user_agent, $http_cookie, and so forth. Note that because these correspond to what the client actually sends, they are not guaranteed to exist and their meaning is defined elsewhere (e.g. in relevant standards).

Furthermore, there are other variables:

[edit] $arg_PARAMETER

This variable contains the value of the GET request variable PARAMETER if present in the query string

[edit] $args

This variable is the GET parameters in request line, e.g. foo=123&bar=blahblah;

[edit] $binary_remote_addr

The address of the client in binary form;

[edit] $body_bytes_sent

The amount of bytes sent as part of the body of the response. Is accurate even when connections are aborted or interrupted.

[edit] $content_length

This variable is equal to line Content-Length in the header of request;

[edit] $content_type

This variable is equal to line Content-Type in the header of request;

[edit] $cookie_COOKIE

The value of the cookie COOKIE;

[edit] $document_root

This variable is equal to the value of directive root for the current request;

[edit] $document_uri

The same as $uri.

[edit] $host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host when the Host input header is absent or has an empty value.

[edit] $hostname

Set to the machine's hostname as returned by gethostname

[edit] $http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;

[edit] $is_args

Evaluates to "?" if $args is set, "" otherwise.

[edit] $limit_rate

This variable allows limiting the connection rate.

[edit] $nginx_version

The version of Nginx that the server is currently running;

[edit] $query_string

The same as $args.

[edit] $remote_addr

The address of the client.

[edit] $remote_port

The port of the client;

[edit] $remote_user

This variable is equal to the name of user, authenticated by the Auth Basic Module;

[edit] $request_filename

This variable is equal to path to the file for the current request, formed from directives root or alias and URI request;

[edit] $request_body

This variable(0.7.58+) contains the body of the request. The significance of this variable appears in locations with directives proxy_pass or fastcgi_pass.

[edit] $request_body_file

Client request body temporary filename;

[edit] $request_completion

Set to "OK" if request was completed successfully. Empty if request was not completed or if request was not the last part of a series of range requests.

[edit] $request_method

This variable is equal to the method of request, usually GET or POST.

Before and including 0.8.20, this variable always evaluates to the method name of the main request, not the current request if the current request is a subrequest.

[edit] $request_uri

This variable is equal to the *original* request URI as received from the client including the args. It cannot be modified. Look at $uri for the post-rewrite/altered URI. Does not include host name. Example: "/foo/bar.php?arg=baz"

[edit] $scheme

The HTTP scheme (i.e. http, https). Evaluated only on demand, for example:

rewrite  ^  $scheme://example.com$uri  redirect;

[edit] $server_addr

Equal to the server address. As a rule, for obtaining the value of this variable is done one system call. In order to avoid system call, it is necessary to indicate addresses in directives listen and to use parameter bind.

[edit] $server_name

The name of the server.

[edit] $server_port

This variable is equal to the port of the server, to which the request arrived;

[edit] $server_protocol

This variable is equal to the protocol of request, usually this HTTP/1.0 or HTTP/1.1.

[edit] $uri

This variable is equal to current URI in the request (without arguments, those are in $args.) It can differ from $request_uri which is what is sent by the browser. Examples of how it can be modified are internal redirects, or with the use of index. Does not include host name. Example: "/foo/bar.html"

[edit] References

Original Documentation