NGINX Web Server Nginx web server

原文地址:http://nginx.com/resources/admin-guide/web-server/html

NGINX Web Server
Nginx web server


This section describes:

  • the most common configuration of a web server
  • how to set up virtual servers and define locations for request processing
  • how to use variables
  • how to return specific status codes
  • how to rewrite the URI of a request
  • how to configure HTTP error pages

本章討論:

  • 最常用的 web server的配置
  • 怎樣搭建虛擬主機以及定義請求過程的位置
  • 怎樣使用變量
  • 怎樣設定返回狀態碼
  • 怎樣重寫一個請求的URL
  • 怎樣配置HTTP錯誤頁

Overall, the configuration of NGINX as a web server is a matter of defining which URLs it can process and how it processes them. On a lower level, the configuration consists of a set of virtual servers that are responsible for processing requests for particular domains or IP addresses.nginx

Each virtual server defines special configuration instances called locations that control processing of specific sets of URIs. Each location defines its own scenario of what happens to requests that are mapped to this location. NGINX provides full control over this process. Each location can proxy the request or return a file. In addition, the URI can be modified, so that the request is redirected to another location or virtual server. Also, a specific error code can be returned and you can configure a specific page to corresponds to each error code.web

總的來講,Nginx 做爲一個Webserver的配置幾乎相同就是定義哪些URL能處理和怎樣處理。express

底層點說,這個配置由一組負責處理特定域名或者IP地址的請求的虛擬server。瀏覽器

每一個虛擬server定義了一個稱爲locations的特有的配置實例來控制能處理的指定的URL。服務器

每一個location定義了對映射到本location的URL處理方式。Nginx經過這個過程提供全局控制。每一個location能代理這個請求或者返回一個文件。另外,這個URL還可以被改動,把這個請求重定向到別的location或者虛擬server。相同。可以返回特定的錯誤碼,並且你可以爲每一個錯誤碼配置一個對應的頁面。app

Configuration File
配置文件

Configuring NGINX is similar to other services in that it has a text-based configuration file written in a particular format. By default this file is named nginx.conf. The location of your nginx.conf depends on the package system used to install NGINX and the operating system. Typically, it is one of /usr/local/nginx/conf/etc/nginx, or /usr/local/etc/nginx directories.less

配置Nginx相似於其它的服務,它有一個基於文本的有着特殊格式的配置文件。默認狀況下這個文件名稱爲nginx.conf。dom

你的nginx.conf的位置取決於安裝Nginx使用的包管理系統和操做系統。一般在/usr/local/nginx/conf, /etc/nginx 或者 /usr/local/etc/nginx 當中一個文件夾中。socket

The configuration file is created using directives and parameters. Each directive ends with a semicolon. You may also add additional instructions within 大braces. Below are some examples.

配置文件是使用指令和參數來建立的。每個指令以分號結束。也可以在括號內加入其它說明,看如下演示樣例:

user             nobody;
error_log        logs/error.log notice;
worker_processes 1;

Using include, you can also split configuration into a hierarchy of files, including file contents:

使用include。可以把配置分散到不一樣層級的文件裏,包括文件內容:

include mime.types;

There are a few special directives referred to as contexts. These contexts are eventshttp,server, and location.

有幾個特殊的指令被稱爲上下文環境,這些上下文環境有 eventshttp,server, 和 location.。

Any directives placed outside of the contexts are considered to be in the main context. The example below shows a full configuration file using contexts.


任務一個在上下文環境以外的指令被看成主環境。

如下這個樣例採用上下文環境展現了一個完事的配置文件。

user nobody; # a directive in the 'main' context

events {
    # configuration of events
}

http {

    # Configuration specific to HTTP and affecting all virtual servers

    server {
        # configuration of virtual server 1

        location /one {
            # configuration for processing URIs with '/one'
        }

        location /two {
            # configuration for processing URIs with '/two'
        }
    }

    server {
        # configuration of virtual server 2
    }
}


As you might guess, configuration related to HTTP resides within the http context. The server context configures a specific virtual server within the http context. Finally, the location context is used within the server contect to instruct NGINX to process a particular set of URIs.

你可能會想,跟HTTP有關的配置放在http上下文環境中。server 這個上下文環境在http上下文中配置一個指定的虛擬服務器。

最後,location上下文環境在server上下文中用以指導Nginx去處理特定一些的URL。

In most cases, a context that is defined inside another context will inherits its directives. When that happens, and you then declare the the same directive on the current level, the directive on the current level will override the inherited one. For more information on context inheritence see the proxy_set_header documentation.

多數狀況下,定義在還有一個上下文環境裏的上下文將繼承所有指令。在這樣的狀況下。假設你在當前層裏聲明瞭相同的指令,當前層的指令將會覆蓋繼承下來的。有關上下文繼承不少其它信息請看:proxy_set_header documentation

For the changes in the configuration file to take effect you have two options. First you can simply restart nginx. Alternatively, you can send the reload signal to upgrade the configuration without interrupting the processing of current requests.

有兩種辦法可以使配置文件的更改生效。第一種是簡單粗暴的從新啓動Nginx。還有一種。你可以發送一個重載信號以更新配置而不用打斷當前請求處理進程。

Setting Up a Virtual Server
搭建虛擬server

To process HTTP requests, your NGINX configuration file should define at least one virtual server. When NGINX processes a request, it will first select the virtual server that will serve the request.

爲了處理HTTP請求,你的Nginx配置文的應該定義至少一個虛擬server。當Nginx要處理一個請求時,首選虛擬server來處理該請求。


Servers are defined using the server directive, which is placed in the http context, for example:

定義服務器使用 server 指令。放在 http 上下文環境中,好比:

http {
    server {
        # Server configuration
    }
}

It is possible to add multiple server directives into the http context to define multiple virtual servers.

在http上下文中可以加入多個server指令來定義多個虛擬服務器;

The server directive should also include a listen directive. This directive specifies the IP address and port (or Unix domain socket and path) which the server will listen. The IP address can be either IPv4 or IPv6. Keep in mind that IPv6 must be specified in the square brackets.

server 指令還應該包括一個 listen 指令。這個指令指定服務器監聽的IP地址和port(或者Unix域套接字和路徑)。IP 地址可以是IPv4或IPv6的。記住IPv6必須要使用方括號指定。

The example below shows configuration of a server that listens on the 127.0.0.1 address and8080 port:

如下這個樣例配置了一個server監聽127.0.0.1這個地址和8080port:

server {
    listen 127.0.0.1:8080;
    # The rest of server configuration
}

If a port is omitted, the standard port will be used. Likewise, if an address is omitted, the server will listen on all addresses. Note that if the listen directive is not specified, the 「standard」 port is 80/tcp and the 「default」 port is 8000/tcp, depending on superuser privileges.

假設port參數省略了。就使標準port。

還有,假設地址省略了,server就監聽所有地址。注意假設listen 指令沒有設置。那麼「標準」port爲 80/tcp 和 默認「port」爲 8000/tcp。使用哪一個取決於超級管理員權限。

If there are several servers that match the IP address and port of the request, NGINX tests the request’s 「Host」 header field against the server_name directives of the server blocks. The parameter of this directive can be an exact name, a wildcard, or a regular expression. A wildcard name includes an asterisk that starts or finishes the name and will match any string. A regular expression should be preceded with a tilde (~). The example below illustrates the case of an exact name.

假設一個請求匹配上多個服務器的IP地址和port,那麼NGINX查找請求頭裏的「Host」字段來相應server塊裏的server_name 指令。

這個指令的參數可以是一個確切的名字,一個通配符或者一個正則表達式。

一個在開頭或者結尾包括星號的通配符名字能匹配不論什麼字符串。一個正則需要以波浪號(~)開頭。

如下舉了一個使用精確名稱的樣例:

server {
    listen      80;
    server_name example.org www.example.org;
    …
}

If several names match the 「Host」 header, NGINX selects one, trying the names in the following order:

假設多個名稱匹配上「Host」頭。Nginx使用下列的順序選擇一個:

  1. Exact name. 
  2. Longest wildcard name starting with an asterisk, such as *.example.org.
  3. Longest wildcard name ending with an asterisk, such as mail.*.
  4. First matching regular expression (in order of appearance in the configuration file).
  1. 精確匹配
  2. 以星號開頭的最長的通配符名字,好比:*.example.org

  3. 以星號結束的最長的通配符名字,好比:mail.*。
  4. 第一個匹配上正則表達式的(以配置文件中的位置爲順序)。

If the 「Host」 header field does not match a server name, NGINX will route the request to the default server for this port. The default server is the first one listed in the nginx.conf file. This will be overridden if the default_server parameter is set in the listen directive within a server context. An example is given below.


假設「Host」頭字段匹配不上不論什麼一個主機名,Nginx將把這個請求路由到該port的默認主機。默認主機是nginx.conf文件中的第一個。

假設某個主機上下文裏的listen指令後跟了default_server參數。那麼這個默認主機將被覆蓋。實比例如如下:

server {
    listen      80 default_server;
    …
}

Configuring Locations
配置locations

One aspect NGINX includes in the virtual server configuration is the ability to send traffic to different proxies or serve different files based on the request URIs. These blocks are defined using the location directive placed within a server directive.

Nginx虛擬主機配置裏的當中一個牛逼之處在於依據請求URLs把流量分發到不一樣的代理或主機。這些功能的組件在server指令中的location指令裏定義。

For example, you can configure the virtual server to send a portion of requests to a proxied server, send another portion to a different proxied server, and serve the rest with files from the local file system. To accommodate this you configure the virtual server to define three location blocks, one for each case.

好比,你可以配置虛擬主機把請求的一部分發給一個代理server。還有一部分發送給還有一臺代理server,剩下的經過本地文件系統的文件來處理。要實現這些功能,你需要在虛擬主機裏定義三個location組件。每部分一個。

NGINX tests request URIs against the parameters of all location directives and applies the directives that reside within the selected location. Inside each location block, it is usually possible (with a few exceptions) to place even more location directives to further split the configuration into parts that are relevant to specific groups of requests.

Nginx針對所有location指令裏的參數來檢測請求URL,應用選中的location中的所有指令。在每個location組件中, 一般(也有例外)會放置不少其它的location指令進一步把配置依據特定的請求羣組分紅幾個部分。

NOTE: In this guide, the word 「location」 refers to a single location directive and its context.

The parameter of the location directive can be a prefix string or a regular expression. A URI should start with a prefix string in order to match it.

注意:在這篇指南中,」location」 這個詞指一個單獨的location指令和他的上下文環境。location 指令的參數可以是一個前綴字符串也可以是一個正則表達式。

一個URI應該從一個前綴字符串開始匹配。

Below is an example of a location with a prefix string parameter. It will match requests such as/some/path/document.html.


如下是一個曾經綴字符串爲參數的location,它將匹配如/some/path/document.html 這種請求。

location /some/path/ {
    …
}

A regular expression is preceded with a tilde (~). In the following example the location which includes a regular expression in the parameter matches URIs that include 「.html」 or 「.htm」.

一個正則表達式是以波浪號(~)開始的,如下這包括了正則表達式的參數的location實例將匹配包括」.html」或者」.htm」的URI。

location ~ \.html?

{ #譯者注:此處幾個意思,應該是 ~\.htm?

纔對吧 … }


Higher priority is given to regular expressions, unless the 「^~」 modifier is used. Among the prefix strings NGINX selects the most specific one (that is, the longest and most complete string). The exact logic for selecting a location to process a request is given below:

正則表達式的優先級更高。除非使用了」^~」修飾符。

在前綴字符串裏Nginx選擇最詳細的(即匹配最長和最多的字符串)。選擇location來處理請求的確切邏輯例如如下:

  1. Test the URI against all prefix strings.
  2. The 「=」 modifier defines an exact match of the URI and a prefix string. If the exact match is found, the search stops.
  3. If the 「^~」 modifier prepends the longest matching prefix string, the regular expressions are not checked.
  4. Store the longest matching prefix string.
  5. Start testing the URI against regular expressions.
  6. Break on the first matching regular expression and use the corresponding location.
  7. If no regular expression matches, use the location corresponding to the stored prefix string.
  1. 針對所有前綴匹配字符串檢測URL
  2. 「=「修飾符定義了一個URL的精確匹配的一個前綴字符串。假設找到精確匹配。搜索中止。
  3. 假設最長匹配前綴串的前面有」^~",那這個正則表達式就不檢測。
  4. 保存最長匹配前綴串。

  5. 開始針對正則表達式檢測URL。
  6. 在第一個匹配的正則表達式處退出搜索,並且使用這個location。
  7. 假設沒有正則匹配上。那麼就使用已存儲的前綴串指向的location。

A typical example of using the 「=」 modifier is with the usage of 「/」. If the 「/」 request needs to be served often, specifying the location parameter as 「= /」 will speed up processing of these requests. As noted above, this is due to the search being stopped after the first comparison.

一個典型的」=「修飾符的使用是和」/「一塊兒使用的。假設」/「請求經常被訪問。那麼設location的參數爲」=/「能加快處理這些請求的速度。如前面所提到的,這是因爲搜索在第一次比較以後就中止了。

location = / {
    ...
}


A location can contain directives that allow you to define how to resolve a request—serve a static file or pass the request to a proxy. In the following example a virtual server has two locations showing each resolution.

location 裏的指令可以定義假設處理一個請求——提供一個靜態文件仍是把請求傳遞給一個代理。

如下這個實例中虛擬主機有兩個location分別實現這兩種方案。

server {
    location / {
        proxy_pass http://www.example.com;
    }

    location /images/ {
        root /data;
    }
}


The proxy_pass directive passes the request to the proxied server located at the URL you supply. The response from the proxied server will then be passed back to the client. In the example above, all requests with URIs that do not start with 「/images/」 will be passed to the proxied server.

 proxy_pass 指令把你請求的請求傳遞給你提供的URL相應的代理server。代理server處理後的響應又返回給client。上例中,所有不以」/images/「開頭的URL請求都將傳遞給代理server。

The root directive specifies the file system path in which the static files are located. The request URI associated with the location is then added to the path to obtain the static files. In the example above, in response to the URI 「/images/example.png」, NGINX will send the 「/data/images/example.png」 file.

 root 指令指定靜態文件在文件系統中的位置。分配到該location的請求URL被加入到路徑後來獲取靜態文件。上例中,Nginx會把」/data/images/example.png」文件發送到URI"/images/exmple.png」的響應裏。

Variables
變量

The nginx.conf file also allow you to set variables. Variables help you create configurations that behave differently depending on defined circumstances. Variables are named values that are calculated at run time and are used in parameters of directives. A variable is denoted by the 「$」 sign at the beginning of its name. Variables define information based upon nginx’s state, such as the properties of the currently processed request.

nginx.conf文件中也可以設置變量。

變量幫你建立依據狀況而行爲可變的配置。命名過的變量將在執行時計算出值以做指令的參數。

變量使用 「$」 符號在其名字前進行標記。變量定義的信息取決於Nginx的狀態,好比前面處理的請求的屬性。

There are plenty of predefined variables, such as the core HTTP variables, but you can also define custom variables using the setmap, and geo directives. Most variables are computed at run time and contain information related to a specific request. For example, $remote_addr contains the client IP address and $uri holds the current URI value.

有大量如 core HTTP 變量的提早定義變量。然而你也可以使用 setmap, 和 geo 指令定義本身定義變量。

多數變量在執行時計算得出並且包括特定請求的相關信息。好比,$remote_addr 包括了clientIP地址,還有$uri收保存當前URI的值。

Returning Specific Codes

返回指定狀態碼

Some website URIs may require immediate return of a response with a specific error or redirect code. An example of this would be if a page has been moved temporarily or permanently. The easiest way to do this is to use the return directive. For example:

有些站點的URL需要直接返回一個帶有指定錯誤碼或者重定向碼的響應。好比當一個頁面被暫時或永久刪除的時候。

實現這個功能最簡單的方法就是直接使用  return  指令。好比:

location /wrong/url {
    return 404;
}


The first parameter of return is a response code. Additionally, the directive may have a second parameter set to the URL of a redirect (for codes 301, 302, 303, and 307) or the text to return in the response body. For example:

return  的第一個參數是響應碼。另外 ,它也可以使用第二個參數設置爲URL或者重定向(對於碼301,302.302,和307)或者放在響應體裏返回的文本。好比:

location /permanently/moved/url {
    return 301 http://www.example.com/moved/here;
}


The return directive can be specified in either location or server context.

return指令在location或server上下文環境裏使用。

Rewriting the URI
重寫URI

A request URI can be modified multiple times during request processing through the use of the

rewrite. This directive has two required and one optional parameters. The first parameter is a regular expression to test the request URI. The second parameter is the URI to replace the current one if it matches the regular expression. The optional third parameter is a flag that can indicate to stop processing further rewrite directives. For example:

一個請求的URL可以在請求處理過程當中使用 rewrite 指令進行屢次改動。這個指令有兩個必須的參數和一個可選參數。第一個參數是檢測請求URI的正則式。第二個參數是用來替換匹配了正則式的URI的。

第三個可選參數是一個指示是否中止進程執行其它的重寫指令的標誌位。

location /users/ {
    rewrite ^/users/(.*)$ /show?

user=$1 break; }



As this example shows, the second parameter users captures though matching of regular expressions.

如例所看到的,第二個參數經過匹配正則工捕捉」users」。

The rewrite directives can be used in both the server and location levels. You can include multiple rewrite directives in the same server or location. The rewrite directives are executed one-by-one in the order of their appearance. The rewrite directives on the virtual server level are executed once when that virtual server is selected.

rewrite指令能同一時候在server和location層使用。可以在同一個server或location裏放多條rewrite指令。

rewrite指令依據前面順序一條一條運行。配置在虛擬主機上的rewrite運行一量虛擬主機被選中就運行。

Once this set of rewriting instruction is processed, a location is selected according to the new URI. Then if a selected location contains rewrite directives, they are executed in turn. If the URI matches any of those, then a search for the new location starts after all defined rewrite directives are processed.

一旦這組重寫指令集被運行了。就依據新的URI選擇一個location。假設被選中的location包括rewrite指令集,就輪流的運行。假設RUI匹配上當中一個,所有定義的rewrite 指令運行完後就開始搜索新的location。

The following example shows rewrite directives in combination with a return directive.

下述樣例展現 了rewrite 指令集與return指令組合使用。

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


This example configuration distinguishes two types of URIs. URIs such as/download/some/media/file are changed to /download/some/mp3/file.mp3. The second rewrite and return are skipped (due to the last flag) but NGINX continues processing the request, which now has a different URI. Similarly, such URIs as /download/some/audio/file are replaced with /download/some/mp3/file.ra. If a URI doesn’t match any of these cases, the return directive comes into action and returns a 403 error code.

上例中。配置了兩類可區分的URI,URI如/download/some/media/file被改動爲 /download/some/mp3/file.mp3。第二個rewrite指令和return指令會跳過(因爲last標誌位)但是Nginx會繼續處理這個擁有新URI的請求。相同的,URL如/download/some/audio/file則被替換爲/download/some/mp3/file.ra。

假設一個URI匹配不上不論什麼一個rewrite,那return指令就生效並返回一個403錯誤碼。

There are two parameters that interrupt processing of rewrite directives:

有兩個參數能中斷rewrite指令集的進程:

  • last stops execution of the rewrite directives in the current virtual server or location, but the search for a location continues. So the rewrite directives in the new location will be executed.
  • last 中止當前虛擬主機或location中的rewrite指令集,但是繼續搜索新的location。所以新的location中的rewrite指令集仍是會被運行。

  • The break parameter as well as the break directive stop processing of rewrite directives on the current level and stop the search of a location. So the rewrite directives in the new location will not be executed.
  • break參數同 break 指令同樣中止當前層的rewrite指令集進程並且中止location的搜索,所以新的location裏的rewrite指令集將不會被運行。

Configuring Error Pages
配置錯誤頁

To configure the pages returned for particular error codes, use the error_page directive. This directive allows you to set rules for a particular error code, such as the URI of a page to return as a response for a particular error code. You could also set error code to substitute for another one. In the following example, the error_page directive sets a page to return in case of a 404 error.

要爲特定的錯誤碼配置頁面,使用error_page 指令。這個指令可以爲特定的錯誤碼設置規則。好比對一個特定的錯誤碼返回的頁面的URI。你也可以使用一個錯誤碼替換還有一個。下例中。error_page 指令爲404錯誤碼設置了一個返回頁面。

error_page 404 /404.html;

Note that this directive does not mean that the error will be returned immediately (this is what return does), but simply provides settings for treating errors when they occur. The error code can come from a proxied server or appear as a result of processing a request by NGINX (for example, 404 pops up when NGINX can’t find a file requested by the client).

注意這個指令並非意味着這個錯誤會直接返回(那是return乾的事),而僅僅是爲處理錯誤的發生提供配置。這個錯誤碼可能來自一個代理server也可能來自Nginx對請求處理的結果(好比,當Nginx找不到client所請求的文件的時候彈出404)。

In the following example, if a page is not found, the 301 code replaces the 404 code, and a redirect to a different URL is made.

如下這個樣例中,假設一個頁面找不到。使用301碼替換404,並且重定向到一個製做好的不一樣的URL。

location /old/path.html {
    error_page 404 =301 http:/example.com/new/path.html;
}


This type of replacement may be useful when a page has a new URI, but clients still try to access it with the old address. The 301 code informs a browser that the page has moved permanently. Setting a 301 code tells the browser to replace the old address with the new one automatically upon return.

這類的替換可能會用在一個頁面更新了URI。但是client還一直訪問舊地址的狀況。301碼用於通知瀏覽器一個頁面被永久的刪除了。在返回時本身主動設置一個301碼告訴瀏覽器更換舊地址爲新地址。

The following configuration is an example of passing a request to the backend when a file is not found. Since the error_page directive below has no status code specified after the equal sign, the response the client gets will have the status code returned by the proxied server (not necessarily 404).

如下這個配置舉例當文件找不到的時候把請求發送給backend。

因爲error_page指令如下在等號後沒有指定狀態碼,所以client拿到的則代理server返回的狀態碼(不必定是404)。

server {
    ...
    location /images/ {
        # Set the root directory to search for the file
        root                   /data/www;

        # Disable logging of errors related to file existence
        open_file_cache_errors off;

        # Make an internal redirect if the file is not found
        error_page             404 = /fetch$uri;
    }

    location /fetch/ {
        proxy_pass             http://backend/;
    }
}


Note that the parameter set for the error_page directive here includes the $uri variable, which holds the URI of the current request. The open_file_cache_errors directive prevents writing an error message if a file is not found. This is not necessary here since missing files will be correctly handled. Due to the use of the error_page directive NGINX makes an internal redirect if a file is not found. More specifically, the /images/some/file URI is replaced with/fetch/images/some/file and a new search for a location starts. As a result, the request ends up in the second location and is proxied.

注意這裏設置的error_page指令的參數包括了$uri這個變量,這個變量保存了當前請求的URI的值。 假設文件找不到,open_file_cache_errors 指令阻止寫錯誤消息。這裏沒有必要因爲丟失的文件能被正確的處理。因爲這裏使用error_page讓Nginx作了一個內部重定向假設文件不存在的話。更詳細的說,images/some/fileURI會被替換爲/fetch/images/some/file並且對開啓一個新的對location的搜索。結果是這個請求在第二個location結束並被代理了。

相關文章
相關標籤/搜索