Table of Contents
What is Nginx?
Basic Commands
最小化配置
Home Operation and Maintenance Nginx What are the basic concepts of Nginx

What are the basic concepts of Nginx

May 16, 2023 pm 05:02 PM
nginx

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
Copy after login

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

[sudo] nginx -s signal
Copy after login

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;
    Copy after login
    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 上下文中的指令 }
    }
    Copy after login
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 }
}
Copy after login

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;
 }
}
Copy after login

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;
 }
}
Copy after login

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;
 }
}
Copy after login

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";
}
Copy after login

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"
Copy after login

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
Copy after login

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;
Copy after login

is an abbreviation from

server_name  netguru.co  www.netguru.co  *.netguru.co;
Copy after login

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
Copy after login

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

listen unix:/var/run/nginx.sock;
Copy after login

你甚至可以使用主机名

listen localhost:80;
listen netguru.co:80;
Copy after login

但请慎用,由于主机可能无法启动 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";
 }
}
Copy after login

root, location, 和 try_files 指令

root 指令

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

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

根据给定的请求,指定 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
Copy after login

location 指令

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

location /foo/ {
 # ...}
Copy after login

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

以上例子将匹配

/foo
/fooo
/foo123
/foo/bar/index.html
...
Copy after login

此外,在给定的上下文中可以使用多个 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"
Copy after login

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

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

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'
Copy after login

try_files 指令

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

try_files $uri index.html =404;
Copy after login

所以对于 /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 / {
 }
}
Copy after login

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

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

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 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to configure cloud server domain name in nginx How to configure cloud server domain name in nginx Apr 14, 2025 pm 12:18 PM

How to configure an Nginx domain name on a cloud server: Create an A record pointing to the public IP address of the cloud server. Add virtual host blocks in the Nginx configuration file, specifying the listening port, domain name, and website root directory. Restart Nginx to apply the changes. Access the domain name test configuration. Other notes: Install the SSL certificate to enable HTTPS, ensure that the firewall allows port 80 traffic, and wait for DNS resolution to take effect.

How to start nginx server How to start nginx server Apr 14, 2025 pm 12:27 PM

Starting an Nginx server requires different steps according to different operating systems: Linux/Unix system: Install the Nginx package (for example, using apt-get or yum). Use systemctl to start an Nginx service (for example, sudo systemctl start nginx). Windows system: Download and install Windows binary files. Start Nginx using the nginx.exe executable (for example, nginx.exe -c conf\nginx.conf). No matter which operating system you use, you can access the server IP

How to check nginx version How to check nginx version Apr 14, 2025 am 11:57 AM

The methods that can query the Nginx version are: use the nginx -v command; view the version directive in the nginx.conf file; open the Nginx error page and view the page title.

How to check the name of the docker container How to check the name of the docker container Apr 15, 2025 pm 12:21 PM

You can query the Docker container name by following the steps: List all containers (docker ps). Filter the container list (using the grep command). Gets the container name (located in the "NAMES" column).

How to run nginx apache How to run nginx apache Apr 14, 2025 pm 12:33 PM

To get Nginx to run Apache, you need to: 1. Install Nginx and Apache; 2. Configure the Nginx agent; 3. Start Nginx and Apache; 4. Test the configuration to ensure that you can see Apache content after accessing the domain name. In addition, you need to pay attention to other matters such as port number matching, virtual host configuration, and SSL/TLS settings.

How to check whether nginx is started How to check whether nginx is started Apr 14, 2025 pm 01:03 PM

How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

How to create a mirror in docker How to create a mirror in docker Apr 15, 2025 am 11:27 AM

Steps to create a Docker image: Write a Dockerfile that contains the build instructions. Build the image in the terminal, using the docker build command. Tag the image and assign names and tags using the docker tag command.

How to start containers by docker How to start containers by docker Apr 15, 2025 pm 12:27 PM

Docker container startup steps: Pull the container image: Run "docker pull [mirror name]". Create a container: Use "docker create [options] [mirror name] [commands and parameters]". Start the container: Execute "docker start [Container name or ID]". Check container status: Verify that the container is running with "docker ps".

See all articles