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
- 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
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 directivesHave 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 } }
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 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 requestsWithin 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
- has the default_server Tag IP-Port Host
- First define IP-Port Host
- If there is no match, reject the connection.
- 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
- The longest wildcard The name starts with an asterisk, such as "*.example.org".
- The longest wildcard name ends with an asterisk, such as "mail.**"
- Matches the regular expression first (as per the configuration file The order in)
- 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:端口值 然而,还可以指定 UNIX-domain 套接字。 你甚至可以使用主机名 但请慎用,由于主机可能无法启动 nginx,导致无法绑定在特定的 TCP Socket。 最后,如果指令不存在,则使用 有了这些知识 – 我们应该能够创建并理解运行 nginx 所需的最低配置。 root, location, 和 try_files 指令 root 指令 root 指令设置请求的根目录,允许 nginx 将传入请求映射到文件系统。 根据给定的请求,指定 nginx 服务器允许的内容 location指令根据请求的 URI 来设置配置。 如果没有指定修饰符,则路径被视为前缀,其后可以跟随任何东西。 以上例子将匹配 此外,在给定的上下文中可以使用多个 location 指令。 Nginx还有一些修饰符可以用于连接location。因为每个修饰符都有自己的优先级,所以它们会影响 location 模块在使用时的行为。 Nginx 会先检查精确匹配。如果找不到,我们会找优先级最高的。如果之前的匹配尝试失败,正则表达式会按照出现的顺序逐个进行测试。至少,最后一个前缀匹配将被使用。 尝试不同的路径,找到一个路径就返回。 所以对于 $uri ( /foo.html ) index.html 如果什么都没找到则返回 404 有趣的是,如果我们在服务器上下文中定义 try_files,然后定义匹配的所有请求的 location —— try_files 将不会执行。 这是因为在服务器上下文中定义的 try_files 是它的 pseudo-location,这是最不可能的位置。因此,location/的定义将比pseudo-location更为明确。 因此,你应该避免在 server 上下文中出现 try_files: 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!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
listen unix:/var/run/nginx.sock;
listen localhost:80;
listen netguru.co:80;
*:80
。最小化配置
# /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";
}
}
server {
listen 80;
server_name netguru.co;
root /var/www/netguru.co;
}
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 [modifier] path
location /foo/ {
# ...}
/foo
/fooo
/foo123
/foo/bar/index.html
...
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"
= - Exact match
^~ - Preferential match
~ && ~* - Regex match
no modifier - Prefix match
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
请求,它将尝试按以下顺序返回文件:server {
try_files $uri /index.html =404;
location / {
}
}
server {
location / {
try_files $uri /index.html =404;
}
}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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

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.

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

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

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.

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