What are the Nginx web server configuration blocks?

coldplay.xixi
Release: 2020-06-29 16:44:02
Original
2556 people have browsed it

Nginx Web server configuration blocks include: 1. Set up the virtual server; 2. Configure the location; 3. Use variables; 4. Return specific status codes; 5. Rewrite the URI in the request; 6. Rewrite HTTP Response; 7. Handle errors.

What are the Nginx web server configuration blocks?

Nginx Web server configuration blocks are:

1. Set up the virtual server

The NGINX configuration file must contain at least one server directive to define the virtual server. When NGINX handles a request, it first selects the virtual server that serves the request.

Virtual servers are defined by server directives in the http context, for example:

http {
    server {
        # Server configuration
    }
}
Copy after login

Multiple server directives can be added to the http context to define multiple virtual servers.

Recommended tutorial: nginx quick start tutorial

serverThe configuration block usually includes a listen directive to specify the server The IP address and port (or Unix domain socket and path) to listen for requests on. Both IPv4 and IPv6 addresses are accepted; enclose the square brackets (.

The following example shows the configuration of a server listening on IP address 127.0.0.1 and port 8080:

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

If the port is omitted, then Use standard ports. Likewise, if an address is omitted, the server will listen on all addresses. If no listen directive is included, the "standard" port is 80/tcp and the "default" port is 8000 /tcp, depending on superuser permissions.

If multiple servers match the requested IP address and port, NGINX will test the requested host header field against the server_name directive in the server block . The argument to server_name can be a full (exact) name, a wildcard, or a regular expression.

A wildcard is a string containing an asterisk (*) at the beginning, end, or both; an asterisk matches any character sequence. NGINX uses Perl syntax for regular expressions; use a tilde (~) before them. This example illustrates an exact name.

server {
    listen      80;
    server_name example.org www.example.org;
    ...
}
Copy after login

If the host header is matched by several names, NGINX The following sequence searches for names and uses the first match it finds to select one:

  • Exact Name (Full Exact Name)

  • The longest wildcard character starting with an asterisk, for example: *.example.org

  • The longest wildcard character ending with an asterisk, such as: mail.*

  • The first matching regular expression (in the order they appear in the configuration file)

If the host header field does not match the server name, NGINX will route the request to The default server for the port that requests arrive at. The default server is the first server listed in the nginx.conf file, unless you include the listen_server parameter in the listen directive to explicitly specify the server as the default.

server {
    listen    80    default_server;
    ...
}
Copy after login

A complete Nginx virtual machine configuration example, here we demonstrate the configuration of two virtual machines, the corresponding domain names are: vhost1.com and vhost2.com, the home directory of the vhost1.com website is /data/www/vhost1, The main directory of the vhost2.com website is in /data/www/vhost2:

server {
    listen       80;
    server_name vhost1.com www.vhost1.com;
    index index.html index.html;
    root  /data/www/vhost1;
    access_log  /var/log/vhost1.com.log;
}
server {
    listen       80;
    server_name vhost2.com www.vhost2.com;
    index index.html index.html;
    root  /data/www/vhost2;
    access_log  /var/log/vhost2.com.log;
}
Copy after login

2. The configuration location

NGINX can be configured according to the request URI. Different proxies send traffic or serve different files. These blocks are defined using location directives placed in the server directive.

For example, you can define three location blocks to instruct a virtual server to The server sends some requests, sends others to different proxy servers, and serves the rest by passing files from the local file system.

NGINX test requests the URI based on the parameters of all location directives, and applies the directives defined in the matching location. Within each location block, it is generally possible (with some exceptions) to place additional location directives to further refine the handling of a specific group of requests.

Note: In this tutorial article, the word location refers to a single location context.

The location directive has two types of parameters: prefix string (path name) and regular expression. For a request URI to match a prefix string, it must start with the prefix string.

The following example location with the pathname parameter matches a request URI starting with /some/path/, such as /some/path/document.html, which does not match /my- site/some/path, because /some/path does not appear at the beginning of the URI.

location /some/path/ {
    ...
}
Copy after login

Regular expressions are preceded by a tilde (~) for case-sensitive matching, or a tilde (~*) for case-insensitive matching. The following example matches a URI containing the string .html or .html with any location.

location ~ \.html? {
    ...
}
Copy after login

To find the location that best matches the URI, NGINX first compares the URI to the location of the prefix string. Then search for the location with a regular expression.

Unless the ^~ modifier is used to give higher priority to the regular expression. Among the prefix strings, NGINX chooses the most specific string (that is, the longest and most complete string). The exact logic for choosing where to handle requests is given below:

  • Tests the prefix string for all URIs. The

  • = (equal sign) modifier defines an exact match between the URI and the prefix string. If an exact match is found, the search stops.

  • 如果^~(插入符号)修饰符预先添加最长匹配前缀字符串,则不会检查正则表达式。

  • 存储最长匹配的前缀字符串。

  • 根据正则表达式测试URI。

  • 断开第一个匹配的正则表达式并使用相应的位置。

  • 如果没有正则表达式匹配,则使用与存储的前缀字符串相对应的位置。

=修饰符的典型用例是/(正斜杠)的请求。 如果请求/是频繁的,则指定=/作为location指令的参数加速处理,因为搜索匹配在第一次比较之后停止。

location = / {
    ...
}
Copy after login

location上下文可以包含定义如何解析请求的指令 - 提供静态文件或将请求传递给代理的服务器。 在以下示例中,匹配第一个location上下文的请求将从/data/images目录中提供文件,并将匹配第二个位置的请求传递给承载 www.example.com 域内容的代理服务器。

server {
    location /images/ {
        root /data;
    }
    location / {
        proxy_pass http://www.example.com;
    }
}
Copy after login

root指令指定要在其中搜索要提供的静态文件的文件系统路径。 与该位置相关联的请求URI将附加到路径,以获取要提供的静态文件的全名。 在上面的示例中,要响应/images/logo.png的请求,NGINX提供服务器本地实际对应文件是:/data/images/logo.png。

proxy_pass指令将请求传递给使用配置的URL访问代理服务器。然后将代理服务器的响应传回客户端。在上面的示例中,所有不以/images/开头的URI的请求都将被传递给代理的服务器(也就是:www.example.com)。

3. 使用变量

可以使用配置文件中的变量,使NGINX进程的请求根据定义的情况而有所不同。 变量是在运行时计算的命名值,用作指令的参数。 一个变量由它的名字开头的$(美元)符号表示。 变量根据NGINX的状态定义信息,例如正在处理的请求的属性。

有许多预定义的变量,如核心HTTP变量,您可以使用set,map和geo指令定义自定义变量。 大多数变量在运行时计算的,并包含与特定请求相关的信息。 例如,$remote_addr包含客户端IP地址,$uri保存当前的URI值。

4. 返回特定状态码

一些网站URI需要立即返回具有特定错误或重定向代码的响应,例如当页面被暂时移动或永久移动时。 最简单的方法是使用return指令。 例如返回未找到的404状态码:

location /wrong/url {
    return 404;
}
Copy after login

返回的第一个参数是响应代码。可选的第二个参数可以是重定向的URL(代码301,302,303和307)或在响应体中返回文本。 例如:

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

返回指令可以包含在 location 和 server 上下文中。

重写URI请求

可以通过使用rewrite指令在请求处理期间多次修改请求URI,该指令具有一个可选参数和两个必需参数。 第一个(必需)参数是请求URI必须匹配的正则表达式。 第二个参数是用于替换匹配URI的URI。 可选的第三个参数是可以停止进一步重写指令的处理或发送重定向(代码301或302)的标志。例如:

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

如该示例所示,用户通过匹配正则表达式捕获第二个参数。

您可以在location 和 server上下文中包含多个rewrite指令。 NGINX按照它们发生的顺序逐个执行指令。 当选择该上下文时,server上下文中的rewrite指令将被执行一次。

在NGINX处理一组rewrite指令之后,它根据新的URI选择一个location上下文。 如果所选location块包含rewrite指令,则依次执行它们。 如果URI与其中任何一个匹配,则在处理所有定义的rewrite指令之后,将搜索新location块。

以下示例显示了与返回指令相结合的rewrite指令。

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

此示例配置区分两组URI。 诸如/download/some/media/file之类的URI更改为/download/some/mp3/file.mp3。由于最后一个标志,所以跳过后续指令(第二次rewrite和return指令),但NGINX继续处理该请求,该请求现在具有不同的URI。类似地,诸如/download/some/audio/file的URI被替换为/download/some/mp3/file.ra。 如果URI与rewrite指令不匹配,则NGINX将403错误代码返回给客户端。

有两个中断处理重写指令的参数:

last - 停止执行当前服务器或位置上下文中的重写指令,但是NGINX会搜索与重写的URI匹配的位置,并且应用新位置中的任何重写指令(URI可以再次更改,往下继续匹配)。

break - 像break指令一样,在当前上下文中停止处理重写指令,并取消搜索与新URI匹配的位置。新位置(location)块中的rewrite指令不执行。

5. 重写HTTP响应

有时您需要重写或更改HTTP响应中的内容,将一个字符串替换为另一个字符串。 您可以使用sub_filter指令来定义要应用的重写。 该指令支持变量和替代链,使更复杂的更改成为可能。

例如,您可以更改引用除代理服务器之外的绝对链接:

location / {
    sub_filter      /blog/ /blog-staging/;
    sub_filter_once off;
}
Copy after login

另一个示例将方法从http://更改为http://,并从请求头域替换本地主机地址到主机名。 sub_filter_once指令告诉NGINX在一个位置(location)内连续应用sub_filter伪指令:

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

请注意,如果发生另一个sub_filter匹配,则使用sub_filter修改的响应部分将不再被替换。

处理错误

使用error_page指令,您可以配置NGINX返回自定义页面以及错误代码,替换响应中的其他错误代码,或将浏览器重定向到其他URI。 在以下示例中,error_page指令指定要返回404页面错误代码的页面(/404.html)。

error_page 404 /404.html;
Copy after login

请注意,此伪指令并不立即返回该错误(返回指令执行该操作),而仅仅是指定发生时如何处理错误。 错误代码可以来自代理服务器,或者在NGINX处理期间发生(例如,当NGINX找不到客户端请求的文件时,显示404对应的结果)。

在以下示例中,当NGINX找不到页面时,它会将代码301替换为代码404,并将客户端重定向http:/example.com/new/path.html。 当客户端仍尝试访问其旧URI的页面时,此配置非常有用。 301代码通知浏览器页面已经永久移动,并且需要在返回时自动替换旧地址。

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

以下配置是在未找到文件时将请求传递给后端的示例。 因为在error_page指令的等号之后没有指定状态代码,所以对客户机的响应具有代理服务器返回的状态代码(不一定是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/;
    }
}
Copy after login

当没有找到文件时,error_page指令指示NGINX进行内部重定向。 error_page指令的最终参数中的$uri变量保存当前请求的URI,该URI在重定向中被传递。

例如,如果没有找到/images/some/file,它将被替换为/fetch/images/some/file,并且新的搜索位置(location)开始。最后请求最终在第二个location上下文中,并被代理到http://backend/

如果没有找到文件,则open_file_cache_errors指令可防止写入错误消息。 因为丢失的文件可被正确地处理,但这不是必需的。

The above is the detailed content of What are the Nginx web server configuration blocks?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template