search
HomeBackend DevelopmentPHP TutorialConfiguration method of Location in Nginx

This article mainly introduces the configuration method of Location in Nginx. It has certain reference value. Now I share it with you. Friends in need can refer to it.

There is a person today A classmate asked about the multi-path matching of Nginx sites?

1.www.domain.com/a needs to return /var/www/domain.com/a/index.html
2. www.domain.com/b Need to return /var/www/domain.com/b/index.html
How to configure Nginx to make it effective?

To solve this problem, the first reaction is to directly use the Nginx location directive to solve it. However, before giving the answer, let us first understand the basics of the Nginx location directive.

Nginx block configuration concept

In the Nginx configuration file, two commonly used blocks (Blocks) are usually used for settings:

1.Server area Block
2.Localtion Block

The block here refers to Block. You can even understand it as the configuration content between the following pair of {}.

Sever block is mainly the configuration of the real host, such as configuring the domain name, IP, port and other contents of the host. Of course, in an Nginx configuration file, we can specify the configuration of multiple Sever blocks.

The Location block is inside the Sever block and is subdivided into configurations for different paths and requests. Because there are usually many URIs in a site, you can also write multiple Location configurations in the Location block settings.

Let’s take a look at the basic syntax of Location configuration first:

location optional_modifier location_match {
 # 这个 {} 里面的配置内容就是一个区块 Block
}

The above optional_modifier configuration items can use regular expressions. The commonly used ones are as follows:

  1. Leave blank. Yes, leaving it blank is also a way to set it. When left blank, the configuration indicates that the request path starts with location_match.

  2. =, the equal sign is still very easy to understand: the request path is exactly equal to the value of the following location_match; leave the first item There is still a difference in being empty.

  3. ~, the floating number (note that it is the floating number entered in English) indicates case-sensitive regular matching.

  4. ~* represents case-insensitive regular matching.

  5. ^~ means that no regular matching is expected to occur here.

The order in which Nginx processes Location blocks

The above explains the basic concepts and common configurations of the location directive. Let’s take a look at the order in which Location takes effect! This is also very important:

After each request comes to Nginx, Nginx will choose the best match for the Location to respond. The specific process of processing is to compare it with the configuration of the location one by one. This step can be divided into For the following steps:

  1. First match the prefix (that is, the configuration where the optional_modifier of the location is empty).

  2. Nginx will then look for the exact matching location configuration based on the URI (that is, the configuration where the optional_modifier of the location is =).

  3. If there is still no match, then match the ^~ configuration first. If a configuration is found, the search process will be stopped and the response content will be returned directly.

  4. If no match is found, case-sensitive regular matching will be performed first, and then case-insensitive regular matching will be performed.

Some examples of Nginx Location configuration:

It’s useless to talk more. After reading so many theories, it’s useless without specific examples to support it, so let’s take a look at the specific ones. Configuration examples:

location  = / {
  # = 等号配置符,只匹配 / 这个路由
}
location /data {
   # 留空配置,会匹配有 /data 开始的路由,后续有匹配会往下匹配。
}
location ^~ /img/ {
  # 注意 ^~ 配置,这里匹配到 /img/ 开始的话,直接就返回了。
}
location ~* .(png|gif|ico|jpg|jpeg)$ {
  # 匹配以 png, gif, ico, jpg or jpeg 结尾的请求;这个通常用来设置图片的请求响应。 
}

Two very practical examples:

1. Simple image hotlink prevention

location ~ .(png|gif|jpe?g)$ {
  valid_referers none blocked yourwebsite.com *.yourwebsite.com;
  # 注意上面写上你的域名就好  
  if ($invalid_referer) {
      return   403;
  }
}

2. For some writable path, prohibiting the execution of php or js steps

location ~* /(media|images|cache|tmp|logs)/.*.(php|jsp|pl|py|asp|cgi|sh)$ {
  return 403;
}

Answer to the question

Finally, let’s look at the answer to the question, which can be similar to It looks like this:

location /a {
   root /var/www/domain.com/a;
}

location /b {
   root /var/www/domain.com/b;
}

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Use nginx to deploy multiple Web Servers on one server

The above is the detailed content of Configuration method of Location in Nginx. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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