1. 程式人生 > >NGINX Web Server Nginx web server

NGINX Web Server Nginx web server

put ide 屬性 local 哪些 mage 特定 ket 制作

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

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.

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.

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

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

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

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

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.

配置Nginx類似於其它的服務,它有一個基於文本的有著特殊格式的配置文件。默認情況下這個文件名稱為nginx.conf。

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

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 events, http,server, and location.

有幾個特殊的指令被稱為上下文環境,這些上下文環境有 events, http,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 set, map, 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 變量的提前定義變量。然而你也能夠使用 set, map, 和 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結束並被代理了。



NGINX Web Server Nginx web server