search
HomeOperation and MaintenanceNginxWhat is the matching logic of Server and Location in Nginx?

Server matching logic

When nginx determines which server block to execute a request, it mainly focuses on the listen and server_name fields in the server block

listen command

The listen field defines the IP and port of the server response. If the listen field is not explicitly configured, the default listening is 0.0.0.0:80 (root) or 0.0.0.0:8080 (Non-root)

listen can be configured as:

  1. A combination of ip and port

  2. A single ip , the default is to listen to port 80

  3. A single port, the default to listen to all ip interfaces

  4. A unix socket path

The last item is usually only used to pass requests between different servers

The rules for selecting the server to use are as follows:

  1. nginx First, convert all "incomplete" listen instructions, such as those without listen fields into listen 0.0.0.0:80, listen 1.1.1.1 into listen 1.1.1.1:80, etc.

  2. nginx creates a server block list that best matches the request based on the requested IP and port. It will first match the server block that specifies a specific IP, and then select the server block that listens to 0.0.0.0. But no matter which case it is , the port must be an exact match

  3. If there is only one best match, then the matching server block will be used to respond to the request, otherwise the server_name directive of each server block will be evaluated

Again, the server_name directive will be evaluated only when the listen directive cannot find the best match.

For example, we assume that the example.com domain name points to 192.168.0.1, and nginx located on 192.168.0.1 has and only the following two server blocks:

# server block 1server {
  listen 192.168.0.1;
  server_name other.com
  ...
}

# server block 2server {
  listen 80;
  server_name example.com
  ...
}

server_name directive

If the best match cannot be obtained according to the listen directive, it will Start parsing the server_name directive. nginx will check the "host" header in the request. This value contains the domain name or IP address that the client is actually trying to request. nginx will match the server_name directive based on this value. The matching rules are as follows:

  1. nginx will try to find a server block that exactly matches the server_name and host values. If multiple exact matches are found, the first matching server block will be used

  2. If no exact matching server block is found, nginx tries to find a server block whose server_name starts with *. If multiple are found, the longest matching server block is selected

  3. If If the server block starting with is not found, it will look for the server block ending with. Similarly, if there are multiple matches, the longest match will be selected

  4. If no server block matching * is found , it will look for a server block that defines server_name using a regular expression (starting with ~). If multiple matches are found, the first match will be used

  5. If no regular expression match is found server block, nginx will select a default server block that matches the listen field. Each IP and port combination can be configured with one and only one default default_server block. If not, the first one in the available list will be selected. A server (the selection at this time is random, the order is not fixed)

Examples are as follows:

(1) Accurate server_name matching, for example:

server {
   listen    80;
   server_name www.domain.com;
   ...
}

(2) String starting with * wildcard:

server {
   listen    80;
   server_name *.domain.com;
   ...
}

(3) String ending with * wildcard:

server {
   listen    80;
   server_name www.*;
   ...
}

(4) Matching regular expression:

server {
   listen    80;
   server_name ~^(?.+)\.domain\.com$;
   ...
}

(5) If none of the above matches, default_server is used. If default_server is not specified, the first available server will be selected. We can specify that when there is no matching host value, an error will be returned to the client. Can be used to prevent others from redirecting spam traffic to your website.

server {
  listen 80  default_server;
  server_name _;  return 444;
}

Let nginx disconnect from the browser by returning 444, the non-standard error code of nginx.

Location matching logic

location syntax analysis

location optional_modifier location_match {
  ...
}

The available modifiers are as follows

What is the matching logic of Server and Location in Nginx?

Determination rules

1. nginx first checks based on Prefixed location matching (that is, matching that does not include regular expressions)

2. If there is a location block using the = modifier that completely matches the requested URL, the location will be used immediately to respond to the request

3. If no location block match with the = modifier is found, the inexact prefix will continue to be calculated, the longest matching prefix will be found based on the given uri, and then the following processing will be performed:

(1) If The longest matching location has the ^~ modifier, and nginx will immediately use this location to respond to the request

(2) If the longest matching location does not have the ^~ modifier, nginx will temporarily store the match. , and then continue subsequent matching

4. After determining and storing the longest matching prefix location block, nginx continues to check the regular expression matching location (case-sensitive/case-insensitive). If there is a regular expression If the required match is met, the location of the first regular expression matching the requested uri will be selected to respond to the request

5. If no regular expression location matching the requested uri is found, the previous location will be used. The longest stored prefix location response request

Supplement

Normally, once you choose to use a certain location to respond to a request, the request will be processed within that location, regardless of other locations. However, certain instructions in the location will trigger new location matching, such as:

(1)try_files

(2)rewrite

(3)error_page

The above is the detailed content of What is the matching logic of Server and Location in Nginx?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
NGINX Unit: Supporting Different Programming LanguagesNGINX Unit: Supporting Different Programming LanguagesApr 16, 2025 am 12:15 AM

NGINXUnit supports multiple programming languages ​​and is implemented through modular design. 1. Loading language module: Load the corresponding module according to the configuration file. 2. Application startup: Execute application code when the calling language runs. 3. Request processing: forward the request to the application instance. 4. Response return: Return the processed response to the client.

Choosing Between NGINX and Apache: The Right Fit for Your NeedsChoosing Between NGINX and Apache: The Right Fit for Your NeedsApr 15, 2025 am 12:04 AM

NGINX and Apache have their own advantages and disadvantages and are suitable for different scenarios. 1.NGINX is suitable for high concurrency and low resource consumption scenarios. 2. Apache is suitable for scenarios where complex configurations and rich modules are required. By comparing their core features, performance differences, and best practices, you can help you choose the server software that best suits your needs.

How to start nginxHow to start nginxApr 14, 2025 pm 01:06 PM

Question: How to start Nginx? Answer: Install Nginx Startup Nginx Verification Nginx Is Nginx Started Explore other startup options Automatically start Nginx

How to check whether nginx is startedHow to check whether nginx is startedApr 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 close nginxHow to close nginxApr 14, 2025 pm 01:00 PM

To shut down the Nginx service, follow these steps: Determine the installation type: Red Hat/CentOS (systemctl status nginx) or Debian/Ubuntu (service nginx status) Stop the service: Red Hat/CentOS (systemctl stop nginx) or Debian/Ubuntu (service nginx stop) Disable automatic startup (optional): Red Hat/CentOS (systemctl disabled nginx) or Debian/Ubuntu (syst

How to configure nginx in WindowsHow to configure nginx in WindowsApr 14, 2025 pm 12:57 PM

How to configure Nginx in Windows? Install Nginx and create a virtual host configuration. Modify the main configuration file and include the virtual host configuration. Start or reload Nginx. Test the configuration and view the website. Selectively enable SSL and configure SSL certificates. Selectively set the firewall to allow port 80 and 443 traffic.

How to solve nginx403 errorHow to solve nginx403 errorApr 14, 2025 pm 12:54 PM

The server does not have permission to access the requested resource, resulting in a nginx 403 error. Solutions include: Check file permissions. Check the .htaccess configuration. Check nginx configuration. Configure SELinux permissions. Check the firewall rules. Troubleshoot other causes such as browser problems, server failures, or other possible errors.

How to start nginx in LinuxHow to start nginx in LinuxApr 14, 2025 pm 12:51 PM

Steps to start Nginx in Linux: Check whether Nginx is installed. Use systemctl start nginx to start the Nginx service. Use systemctl enable nginx to enable automatic startup of Nginx at system startup. Use systemctl status nginx to verify that the startup is successful. Visit http://localhost in a web browser to view the default welcome page.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.