nginx 集群系列 - nginx 基本功能 - Web服务器

nginx 集群系列 - nginx 基本功能 - Web服务器

Web服务器

关键词:配置虚拟服务器和位置,使用变量,重写的uri,并定制错误页面。

如果尚未安装nginx,请参阅nginx安装和调优
关于配置文件的更多信息,请参阅NGINX 配置文件.

Each virtual server for HTTP traffic 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 Plus 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 correspond to each error code.

设置虚拟服务器

NGINX 配置文件必须包括至少一个 server指令来定义一个虚拟服务器。当NGINX 处理请求时,它首先选择为请求提供服务的虚拟服务器。

虚拟服务器定义在http里的server,例如:

http {
    server {
        # Server configuration
    }
}

可以在http上下文中配置多个server 指令,来定义多个虚拟服务器。

在server 块内通常包含 一个listen 指令,用来指定该虚拟服务器要监听的IP和端口。

以下例子的服务器的配置监听了IP地址127.0.0.1的8080端口:

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

如果省略一个端口,使用标准端口。同样的,如果省略了一个地址,服务器监听所有地址。如果 listen不包括指令,“标准”端口 80/tcp“默认”端口 8000/tcp根据超级用户特权。

如果有多个服务器相匹配的IP地址和端口的请求,请求的NGINX 测试 Host头字段的 server_name指令的 server块。的参数 server_name可以完整的(具体)的名字,一个通配符,或者一个正则表达式。通配符是一个字符串,包含星号(*)开始,结束,或两者兼而有之;星号匹配任意字符序列。NGINX 使用Perl正则表达式的语法;它们之前与波浪号(~)。这个例子说明了一个确切的名字。

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

}
如果多个名称匹配 Host头,NGINX 选择一个通过搜索名字按照以下顺序和使用它查找到的第一个匹配项:

  1. 确切的名字
  2. 最长的通配符以开始,如 .example.org
  3. 最长的通配符以结尾 ,mail.
  4. 第一个被匹配的正则表达式(在配置文件中出现的顺序)
    如果 Host头字段不匹配服务器名称,NGINX 将请求路由到默认请求到达服务器的端口。默认的服务器是第一个列入nginx。配置文件,除非你包括 default_server参数 listen指令来显式地指定一个服务器作为默认。
server {
    listen      80 default_server;
    ...
}
配置location

NGINX 可以发送traffic到不同的代理或服务不同的文件,基于请求的uri。这些块定义使用 location指令放在一个 server指令。

例如,您可以定义三个 location块来指导虚拟服务器发送一些请求一个代理服务器,其他请求发送到不同的代理服务器,其余的服务请求通过交付文件从本地文件系统。

NGINX 测试请求uri参数的所有 location指令和应用中定义的指令匹配位置。在每个 location块,它通常是可能的(除了少数例外)的地方更多 location指令进一步精炼处理特定组的请求。

注意:在本指南中,location是指一个 location上下文。

location指令有两种类型的参数:前缀字符串(路径名)和正则表达式。一个请求URI匹配一个前缀字符串,它必须始于前缀字符串。

The following sample location with a pathname parameter matches request URIs that begin with /some/path/, such as /some/path/document.html. (It does not match /my-site/some/path because /some/path does not occur at the start of that URI.)下面匹配/some/path/作为前缀的例子:

location /some/path/ {
    ...
}

A regular expression is preceded with the tilde (~) for case-sensitive matching, or the tilde-asterisk (~*) for case-insensitive matching. The following example matches URIs that include the string .html or .htm in any position.

location ~ \.html? {
    ...
}

为了找到最匹配的location URI,NGINX 会先比较前缀字符串URI。然后搜索匹配的正则表达式。

正则表达式优先级更高,除非使用^~。NGINX 会选择前缀匹配中最精确的一个(也就是说,最长和最完整的字符串)。选择location的顺序:

  1. 比对所有的URI前缀字符串。
  2. “=”定义的精确匹配的URI和前缀字符串。如果发现精确匹配,搜索停止。
  3. 如果 “^~”优先匹配最长前缀字符串,而且不检查正则表达式。
  4. 存储已匹配的最长前缀字符串。
  5. URI比对正则表达式。
  6. 选出第一个匹配的正则表达式,使用相应的location。
  7. 如果没有匹配的正则表达式,使用存储字符串相对应的location。

A typical use case for the = modifier is requests for / (forward slash). If requests for / are frequent, specifying = / as the parameter to the location directive speeds up processing, because the search for matches stops after the first comparison.

location = / {
    ...
}

A location context can contain directives that define how to resolve a request – either serve a static file or pass the request to a proxied server. In the following example, requests that match the first location context are served files from the /data directory and the requests that match the second are passed to the proxied server that hosts content for the www.example.com domain.

server {
    location /images/ {
        root /data;
    }

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

The root directive specifies the file system path in which to search for the static files to serve. The request URI associated with the location is appended to the path to obtain the full name of the static file to serve. In the example above, in response to a request for /images/example.png, NGINX Plus delivers the file /data/images/example.png.

The proxy_pass directive passes the request to the proxied server accessed with the configured URL. The response from the proxied server is then passed back to the client. In the example above, all requests with URIs that do not start with /images/ are be passed to the proxied server.

使用变量

You can use variables in the configuration file to have NGINX Plus process requests differently depending on defined circumstances. Variables are named values that are calculated at runtime and are used as parameters to directives. A variable is denoted by the $ (dollar) sign at the beginning of its name. Variables define information based upon NGINX’s state, such as the properties of the request being currently processed.

There are a number of predefined variables, such as the core HTTP variables, and you can define custom variables using the set, map, and geo directives. Most variables are computed at runtime and contain information related to a specific request. For example, remoteaddrcontainstheclientIPaddressand uri holds the current URI value.

返回特定的状态码

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

location /wrong/url {
    return 404;
}

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

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

The return directive can be included in both the location and server contexts.

URI请求重写

A request URI can be modified multiple times during request processing through the use of the rewrite directive, which has one optional and two required parameters. The first (required) parameter is the regular expression that the request URI must match. The second parameter is the URI to substitute for the matching URI. The optional third parameter is a flag that can halt processing of further rewrite directives or send a redirect (code 301 or 302). For example:

location /users/ {
    rewrite ^/users/(.*)$ /show?user=$1 break;
}

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

You can include multiple rewrite directives in both the server and location contexts. NGINX Plus executes the directives one-by-one in the order they occur. The rewrite directives in a server context are executed once when that context is selected.

After NGINX processes a set of rewriting instructions, it selects a location context according to the new URI. If the selected location contains rewrite directives, they are executed in turn. If the URI matches any of those, a search for the new location starts after all defined rewrite directives are processed.

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

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

This example configuration distinguishes between two sets of URIs. URIs such as /download/some/media/file are changed to /download/some/mp3/file.mp3. Because of the last flag, the subsequent directives (the second rewrite and the return directive) are skipped but NGINX Plus continues processing the request, which now has a different URI. Similarly, URIs such as /download/some/audio/file are replaced with /download/some/mp3/file.ra. If a URI doesn’t match either rewrite directive, NGINX Plus returns the 403 error code to the client.

There are two parameters that interrupt processing of rewrite directives:

  • last – Stops execution of the rewrite directives in the current server or location context, but NGINX Plus searches for locations that match the rewritten URI, and any rewrite directives in the new location are applied (meaning the URI can be changed again).
  • break – Like the break directive, stops processing of rewrite directives in the current context and cancels the search for locations that match the new URI. The rewrite directives in the new location are not executed.
HTTP响应重写

Sometimes you need to rewrite or change the content in an HTTP response, substituting one string for another. You can use the sub_filter directive to define the rewrite to apply. The directive supports variables and chains of substitutions, making more complex changes possible.

For example, you can change absolute links that refer to a server other than the proxy:

location / {
    sub_filter      /blog/ /blog-staging/;
    sub_filter_once off;
}

Another example changes the method from http:// to https:// and replaces the localhost address to the host name from the request header field. The sub_filter_once directive tells NGINX to apply sub_filter directives consecutively within a location:

location / {
    sub_filter     'href="http://127.0.0.1:8080/'    'href="https://$host/';
    sub_filter     'img src="http://127.0.0.1:8080/' 'img src="https://$host/';
    sub_filter_once on;
}

Note that the part of the response already modified with the sub_filter will not be replaced again if another sub_filter match occurs.

处理错误

With the error_page directive, you can configure NGINX Plus to return a custom page along with an error code, substitute a different error code in the response, or redirect the browser to a different URI. In the following example, the error_page directive specifies the page (/404.html) to return with the 404 error code.

error_page 404 /404.html;
Note that this directive does not mean that the error is returned immediately (the return directive does that), but simply specifies how to treat errors when they occur. The error code can come from a proxied server or occur during processing by NGINX Plus (for example, the 404 results when NGINX Plus can’t find the file requested by the client).

In the following example, when NGINX Plus cannot find a page, it substitutes code 301 for code 404, and redirects the client to http:/example.com/new/path.html. This configuration is useful when clients are still trying to access a page at its old URI. The 301 code informs the browser that the page has moved permanently, and it needs to replace the old address with the new one automatically upon return.

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

The following configuration is an example of passing a request to the back end when a file is not found. Because there is no status code specified after the equals sign in the error_page directive, the response to the client has the status code returned by the proxied server (not necessarily 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/;
    }
}

The error_page directive instructs NGINX Plus to make an internal redirect when a file is not found. The $uri variable in the final parameter to the error_page directive holds the URI of the current request, which gets passed in the redirect.

For example, if /images/some/file is not found, it 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 context and is proxied to http://backend/.

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 are correctly handled.

参考官方文档:https://www.nginx.com/resources/admin-guide/nginx-web-server/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值