Home  >  Article  >  Operation and Maintenance  >  What are the basic concepts of Nginx

What are the basic concepts of Nginx

WBOY
WBOYforward
2023-05-16 17:02:484511browse

What are the basic concepts of Nginx

What is Nginx?

Nginx was originally created as a web server to solve the problems of C10k. As a web server, it can serve your data at blazing speeds. But Nginx is more than just a web server, you can also use it as a reverse proxy to easily integrate with slower upstream servers such as Unicorn or Puma. You can distribute traffic appropriately (load balancer), stream media, dynamically resize images, cache content, and more. The basic nginx architecture consists of a master process and its worker processes. The master reads the configuration file and maintains the worker process, and the worker actually processes the request.

Basic Commands

To start nginx, just enter:

[sudo] nginx

When your nginx instance is running, you can send the corresponding signal by To manage it:

[sudo] nginx -s signal

Available signals:

  • stop – Quick shutdown

  • ##quit – Graceful shutdown ( Wait for the worker thread to complete processing)

  • reload – Reload the configuration file

  • reopen – Reopen the log file

Command and context

nginx configuration file, the default location includes:

  • /etc/nginx /nginx.conf,

  • ##/usr/local/etc/nginx/nginx.conf

    , or

  • /usr/local/nginx/conf/nginx.conf

  • The configuration file consists of the following parts:

    Directives– Optional, containing name and parameters, ending with a semicolon
  • gzip on;
    Context– In chunks, you can declare directives– similar Scope in programming languages
  • worker_processes 2; # 全局上下文指令http {              # http 上下文   gzip on;        # http 上下文中的指令 server {          # server 上下文   listen 80;      # server 上下文中的指令 }
    }
Instruction type

When using the same instruction to operate in different inheritance models, it must Be cautious. There are three types of directives, each with its own inheritance model.

Normal directives

Have unique values ​​in each context. Also, it can only be defined once in the current context. Overriding a parent's value in a child context is only valid in the current child context.

gzip on;
gzip off; # 非法,不能在同一个上下文中指定同一普通指令2次server {
 location /downloads {
   gzip off;
 }

 location /assets {
   # gzip is on here }
}

Array Directives

Adding multiple directives in the same context will add multiple values ​​instead of full coverage. Defining a directive in a child context will override the value in the parent context.

error_log /var/log/nginx/error.log;
error_log /var/log/nginx/error_notive.log notice;
error_log /var/log/nginx/error_debug.log debug;

server {
 location /downloads {
   # 下面的配置会覆盖父级上下文中的指令   error_log /var/log/nginx/error_downloads.log;
 }
}

Action Instructions

Action is an instruction to change things. Depending on the module's needs, the behavior it inherits may vary. For example, the rewrite command will be executed as long as it matches:

server {
 rewrite ^ /foobar;

 location /foobar {
   rewrite ^ /foo;
   rewrite ^ /bar;
 }
}

If the user wants to try to obtain /sample:

    server's rewrite will be executed, from /sample rewrite to /foobar
  • location /foobar will be executed by the first rewrite matching
  • location, rewriting from /foobar to /foo
  • The second rewrite execution of location, rewrite from /foo to /bar
  • return directive provides different behavior:
server {
 location / {
   return 200;
   return 404;
 }
}

In the above case, return 200 immediately.

Handling requests

Within Nginx, you can specify multiple virtual servers, and each virtual server is described with the server{} context.

server {
 listen      *:80 default_server;
 server_name netguru.co;

 return 200 "Hello from netguru.co";
}

server {
 listen      *:80;
 server_name foo.co;

 return 200 "Hello from foo.co";
}

server {
 listen      *:81;
 server_name bar.co;

 return 200 "Hello from bar.co";
}

This will tell Nginx how to handle incoming requests. When checking a given IP port combination, Nginx will first test which virtual host has the listen directive set.

Then, the value of the server_name directive will detect the Host header (which stores the host domain name).

Nginx will select virtual hosts in the following order:

    The IP-port host matching the sever_name directive
  1. has the default_server Tag IP-Port Host
  2. First define IP-Port Host
  3. If there is no match, reject the connection.
  4. For example, the following example:
Request to foo.co:80     => "Hello from foo.co"Request to www.foo.co:80 => "Hello from netguru.co"Request to bar.co:80     => "Hello from netguru.co"Request to bar.co:81     => "Hello from bar.co"Request to foo.co:81     => "Hello from bar.co"

server_name directiveserver_name directive accepts multiple values . It also handles wildcard matching and regular expressions.

server_name netguru.co www.netguru.co; # exact matchserver_name *.netguru.co;              # wildcard matchingserver_name netguru.*;                 # wildcard matchingserver_name  ~^[0-9]*\.netguru\.co$;   # regexp matching

When there is ambiguity, nginx will use the following command:

    Exact name
  1. The longest wildcard The name starts with an asterisk, such as "*.example.org".
  2. The longest wildcard name ends with an asterisk, such as "mail.**"
  3. Matches the regular expression first (as per the configuration file The order in)
  4. Nginx will store three hash tables for storing specific names, wildcards starting with an asterisk, and wildcards ending with an asterisk. If the result is not in any table, the regular expression tests will be done sequentially.

It is worth remembering that

server_name .netguru.co;

is an abbreviation from

server_name  netguru.co  www.netguru.co  *.netguru.co;

is a little different,

.netguru.co

is stored in the second table, which means it's a bit slower than explicitly declared.

listen Command

在很多情况下,能够找到 listen 指令,接受IP:端口值

listen 127.0.0.1:80;
listen 127.0.0.1;    # by default port :80 is usedlisten *:81;
listen 81;           # by default all ips are usedlisten [::]:80;      # IPv6 addresseslisten [::1];        # IPv6 addresses

然而,还可以指定 UNIX-domain 套接字。

listen unix:/var/run/nginx.sock;

你甚至可以使用主机名

listen localhost:80;
listen netguru.co:80;

但请慎用,由于主机可能无法启动 nginx,导致无法绑定在特定的 TCP Socket。

最后,如果指令不存在,则使用 *:80

最小化配置

有了这些知识 – 我们应该能够创建并理解运行 nginx 所需的最低配置。

# /etc/nginx/nginx.confevents {}                   # events context needs to be defined to consider config validhttp {
server {
   listen 80;
   server_name  netguru.co  www.netguru.co  *.netguru.co;

   return 200 "Hello";
 }
}

root, location, 和 try_files 指令

root 指令

root 指令设置请求的根目录,允许 nginx 将传入请求映射到文件系统。

server {
 listen 80;
 server_name netguru.co;
 root /var/www/netguru.co;
}

根据给定的请求,指定 nginx 服务器允许的内容

netguru.co:80/index.html     # returns /var/www/netguru.co/index.htmlnetguru.co:80/foo/index.html # returns /var/www/netguru.co/foo/index.html

location 指令

location指令根据请求的 URI 来设置配置。location [modifier] path

location /foo/ {
 # ...}

如果没有指定修饰符,则路径被视为前缀,其后可以跟随任何东西。

以上例子将匹配

/foo
/fooo
/foo123
/foo/bar/index.html
...

此外,在给定的上下文中可以使用多个 location 指令。

server {
 listen 80;
 server_name netguru.co;
 root /var/www/netguru.co;

 location / {
   return 200 "root";
 }

 location /foo/ {
   return 200 "foo";
 }
}
netguru.co:80   /       # => "root"netguru.co:80   /foo    # => "foo"netguru.co:80   /foo123 # => "foo"netguru.co:80   /bar    # => "root"

Nginx还有一些修饰符可以用于连接location。因为每个修饰符都有自己的优先级,所以它们会影响 location 模块在使用时的行为。

=           - Exact match
^~          - Preferential match
~ && ~*     - Regex match
no modifier - Prefix match

Nginx 会先检查精确匹配。如果找不到,我们会找优先级最高的。如果之前的匹配尝试失败,正则表达式会按照出现的顺序逐个进行测试。至少,最后一个前缀匹配将被使用。

location /match {
 return 200 'Prefix match: matches everything that starting with /match';
}

location ~* /match[0-9] {
 return 200 'Case insensitive regex match';
}

location ~ /MATCH[0-9] {
 return 200 'Case sensitive regex match';
}

location ^~ /match0 {
 return 200 'Preferential match';
}

location = /match {
 return 200 'Exact match';
}
/match/    # => 'Exact match'/match0    # => 'Preferential match'/match2    # => 'Case insensitive regex match'/MATCH1    # => 'Case sensitive regex match'/match-abc # => 'Prefix match: matches everything that starting with /match'

try_files 指令

尝试不同的路径,找到一个路径就返回。

try_files $uri index.html =404;

所以对于 /foo.html 请求,它将尝试按以下顺序返回文件:

  1. $uri ( /foo.html )

  2. index.html

  3. 如果什么都没找到则返回 404

有趣的是,如果我们在服务器上下文中定义 try_files,然后定义匹配的所有请求的 location —— try_files 将不会执行。

这是因为在服务器上下文中定义的 try_files 是它的 pseudo-location,这是最不可能的位置。因此,location/的定义将比pseudo-location更为明确。

server {
 try_files $uri /index.html =404;

 location / {
 }
}

因此,你应该避免在 server 上下文中出现 try_files:

server {
 location / {
   try_files $uri /index.html =404;
 }
}

The above is the detailed content of What are the basic concepts of Nginx. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete