search
HomeOperation and MaintenanceNginxDetailed explanation of nginx location directive

Detailed explanation of nginx location directive

Which nginx variable does location match?

$request_uri

What are the matching types of location?

= starts with Indicates an exact match starting with

^~. Note that this is not a regular expression (it is a string match with increased priority) – its purpose is to take precedence over regular expression matching. If the location is the best match, regular expression detection is no longer performed.

~ The beginning of indicates case-sensitive regular matching;

~* The beginning of indicates case-insensitive regular matching

!~ && !~*: Indicates case-sensitive non-matching regular and case-insensitive non-matching regular

String matching

/Universal matching, if there is no other match, any request will match

location search order

Exact match first =

Secondly match ^~

Then perform regular matching according to the order of the configuration file

Finally, hand it over to/for general matching

Note:

When a match is successful, the matching will be stopped immediately and the request will be processed according to the current matching rules.

Special note: String matching will be searched first, but only the most recent will be recorded. Long match, and then continue to search for regular matches. If there is a regular match, the regular match is hit. If there is no regular match, the longest string match is hit. (If ^~ is the longest match, it will hit directly and stop searching for regular expressions)

Exact match

location = /images/test.png {
    echo 'config1';
}
location  /images/test.png {
    echo 'config2';
}
location \/images\/test\.png$ {
    echo 'config3';
}

If requested at this timehttp:/ /127.0.0.1/images/test.png What will be output?

Output config1, there is no doubt that exact matching has the highest priority!

Special case of exact matching

location = / {
    index index.html;
}
location / {
    echo 'config2';
}

At this time, what will be output if http://127.0.0.1 is entered?

is the output of config2. Why does the exact matching priority not work?

Yes, exact matching still works. When requesting a directory (not a specific file), nginx will internally direct the request to the index file.

The real request at this time is http://127.0.0.1/index.html, this is config2 and it is hit!

, so exact matching should not be used to match /

characters String search and regular search

location /images/test.png {
    echo 'config1';
}
location ^~ /images/ {
    echo 'config2';
}
location ~ \/images\/test\.png$ {
    echo 'config3';
}
location ~ \/images\/ {
    echo 'config4';
}

If you request http://127.0.0.1/images/test.png at this time, what will be output?

is of course config3, and the regular pattern hits

(although config1 is the longest matching string, only recording is done at this time, and the regular matching must be searched later, then config3 Regular match hits),

If you look carefully, you can find that config4 is also matched successfully, but the regular matching order is matched according to the definition order of location, so config3 hits the .

character Improvement of string matching priority (^~)

location /images/ {
    echo 'config1';
}
location ^~ /images/test.png {
    echo 'config2';
}
location ~ /images/test\.png$ {
    echo 'config3';
}
location ~ \/images\/ {
    echo 'config4';
}

If you request http://127.0.0.1/images/test.png at this time, what will be output?

is of course config2, the first match hits

(because string matching is searched first, at this time it is found that config2 is the longest string match and is ^~ Matching method, so stop searching for regular expressions and hit directly!)

So the ^~ symbols here are special, in order to increase the priority of string matching and take precedence over regular matching.

Related recommendations: "Nginx Tutorial"

The above is the detailed content of Detailed explanation of nginx location directive. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:cnblogs. If there is any infringement, please contact admin@php.cn delete
NGINX's Key Features: Performance, Scalability, and SecurityNGINX's Key Features: Performance, Scalability, and SecurityApr 13, 2025 am 12:09 AM

NGINX improves performance through its event-driven architecture and asynchronous processing capabilities, enhances scalability through modular design and flexible configuration, and improves security through SSL/TLS encryption and request rate limiting.

NGINX vs. Apache: Web Hosting and Traffic ManagementNGINX vs. Apache: Web Hosting and Traffic ManagementApr 12, 2025 am 12:04 AM

NGINX is suitable for high concurrency and low resource consumption scenarios, while Apache is suitable for scenarios that require complex configurations and functional extensions. 1.NGINX is known for handling large numbers of concurrent connections with high performance. 2. Apache is known for its stability and rich module support. When choosing, it must be decided based on specific needs.

NGINX: The Versatile Tool for Modern Web ApplicationsNGINX: The Versatile Tool for Modern Web ApplicationsApr 11, 2025 am 12:03 AM

NGINXisessentialformodernwebapplicationsduetoitsrolesasareverseproxy,loadbalancer,andwebserver,offeringhighperformanceandscalability.1)Itactsasareverseproxy,enhancingsecurityandperformancebycachingandloadbalancing.2)NGINXsupportsvariousloadbalancingm

Nginx SSL/TLS Configuration: Securing Your Website with HTTPSNginx SSL/TLS Configuration: Securing Your Website with HTTPSApr 10, 2025 am 09:38 AM

To ensure website security through Nginx, the following steps are required: 1. Create a basic configuration, specify the SSL certificate and private key; 2. Optimize the configuration, enable HTTP/2 and OCSPStapling; 3. Debug common errors, such as certificate path and encryption suite issues; 4. Application performance optimization suggestions, such as using Let'sEncrypt and session multiplexing.

Nginx Interview Questions: Ace Your DevOps/System Admin InterviewNginx Interview Questions: Ace Your DevOps/System Admin InterviewApr 09, 2025 am 12:14 AM

Nginx is a high-performance HTTP and reverse proxy server that is good at handling high concurrent connections. 1) Basic configuration: listen to the port and provide static file services. 2) Advanced configuration: implement reverse proxy and load balancing. 3) Debugging skills: Check the error log and test the configuration file. 4) Performance optimization: Enable Gzip compression and adjust cache policies.

Nginx Caching Techniques: Improving Website PerformanceNginx Caching Techniques: Improving Website PerformanceApr 08, 2025 am 12:18 AM

Nginx cache can significantly improve website performance through the following steps: 1) Define the cache area and set the cache path; 2) Configure the cache validity period; 3) Set different cache policies according to different content; 4) Optimize cache storage and load balancing; 5) Monitor and debug cache effects. Through these methods, Nginx cache can reduce back-end server pressure, improve response speed and user experience.

Nginx with Docker: Deploying and Scaling Containerized ApplicationsNginx with Docker: Deploying and Scaling Containerized ApplicationsApr 07, 2025 am 12:08 AM

Using DockerCompose can simplify the deployment and management of Nginx, and scaling through DockerSwarm or Kubernetes is a common practice. 1) Use DockerCompose to define and run Nginx containers, 2) implement cluster management and automatic scaling through DockerSwarm or Kubernetes.

Advanced Nginx Configuration: Mastering Server Blocks & Reverse ProxyAdvanced Nginx Configuration: Mastering Server Blocks & Reverse ProxyApr 06, 2025 am 12:05 AM

The advanced configuration of Nginx can be implemented through server blocks and reverse proxy: 1. Server blocks allow multiple websites to be run in one instance, each block is configured independently. 2. The reverse proxy forwards the request to the backend server to realize load balancing and cache acceleration.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)