> For the complete documentation index, see [llms.txt](https://bohans.gitbook.io/devops/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://bohans.gitbook.io/devops/ngnix/ji-chu-zhi-shi/2.-nginx-pei-zhi/2.2-pei-zhi-zhi-ling/location.md).

# location

在Nginx的官方文档中定义的<mark style="color:blue;">**location**</mark>的语法结构为：

```nginx
location [ = | ~ | ~* | ^~ ] uri 
{ 
    ... 
}
```

* <mark style="color:blue;">**uri**</mark>变量是待匹配的请求字符串，可以是不含正则表达的字符串，如 /myserver.php等；也可以是包含有正则表达的字符串，如.php$（表示以.php结尾的URL）等。为了下文叙述方便，我们约定，**不含正则表达的uri**称为“<mark style="color:blue;">**标准uri**</mark>”，**使用正则表达式的uri**称为“<mark style="color:blue;">**正则uri**</mark>”。
* <mark style="color:blue;">**方括号里的部分**</mark>，是可选项，用来改变请求字符串与 uri 的匹配方式。
  * 在<mark style="color:orange;">**不添加此选项**</mark>时，Nginx服务器首先在server块的多个location块中搜索是否有**标准uri**和请求字符串匹配，如果有多个可以匹配，就记录匹配度最高的一个。然后，服务器再用location块中的**正则uri**和请求字符串匹配，当第一个正则uri匹配成功，结束搜索，并使用这个location块处理此请求；如果正则匹配全部失败，就使用刚才记录的匹配度最高的location块处理此请求。
  * “<mark style="color:orange;">**=**</mark>”，用于**标准uri**前，要求请求字符串与uri严格匹配。**如果已经匹配成功，就停止继续向下搜索并立即处理此请求**。
  * “<mark style="color:orange;">**\~**</mark>”，用于表示**uri包含正则表达式**，并且**区分大小写**。
  * “<mark style="color:orange;">**\~\***</mark>”，用于表示**uri包含正则表达式**，并且**不区分大小写**。
  * “<mark style="color:orange;">**^\~**</mark>”，用于**标准uri**前，**要求Nginx服务器找到标识uri和请求字符串匹配度最高的location后，立即使用此location处理请求，而不再使用location块中的正则uri和请求字符串做匹配**。

{% hint style="warning" %}
在浏览器传送URI时会对一部分字符进行URL编码，比如空格被编码为“%20”，问号被编码为“%3f”等。

“<mark style="color:orange;">**^\~**</mark>”有一个特点是，它**对uri中的这些符号将会进行编码处理**。比如，如果location块收到的URI为“/html/%20/data”，则当Nginx服务器搜索到配置为“^～ /html/ /data”的location时，可以匹配成功。
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://bohans.gitbook.io/devops/ngnix/ji-chu-zhi-shi/2.-nginx-pei-zhi/2.2-pei-zhi-zhi-ling/location.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
