Nginx的location指令怎么用?

Syntax: location [ = | ~ | ~* | ^~ ] uri { … }
location @name { … }
Default:
Context: server, location

根据请求的URL设置处理逻辑

匹配工作会在解码%XX形式的参数后进行,同时也会将“.” 和 “..”依据网址进行转换,同时也会将两个甚至多个斜杠压缩成一个斜杠。

一个location定义可以基于前缀字符串(prefix string), 或者正则表达式(regular expression). 正则表达式又分为两种:“~*”不区分大小写,“~”区分大小写。为了找到最终的location定义,需要遵循以下逻辑:nginx首先检查以前缀字符串方式定义的location, 如果请求的网址被多个前缀字符串匹配,则最长的那个会被选择并记住。接下来正则表达式定义会被检查,检查顺序按照配置的先后顺序。正则表达式的检查,只要找到一个匹配就立刻中止,对应的配置会被使用。如果正则表达式定义没有符合要求的,则使用之前记住的最长的前缀字符串式定义。

Location配置块可以嵌套定义。上述规则的例外情况请见下文:

如果最长的前缀式匹配带有“^~”修饰符,则不会检查正则表达式定义。

使用”=”修饰符来定义完全匹配,如果找到了完全匹配的location定义则规则搜索终止。

比如,请求”/”经常发生,定义“location = /”可以加速此类请求的处理速度,因为找到此规则即可终止搜索。

在nginx0.7.1版本到0.8.41版本,即使前缀location没有”=”或“^~”修饰符,也会直接终止,同时不会检查正则式定义。

《Nginx的location指令怎么用?》有1,457条评论

  1. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  2. All the companies in World & 50,000 Cold Emails –

    The Database:

    25 Million Companies Worldwide
    Instantly Delivery
    Last Update: 7 October 2025
    Sample of the Database

    Emails:

    50 thousands emails of your choice from the database
    You pick the industries, location
    We setup the mail system and domains for you
    Responses go directly to you
    Emails are verified for you and delivered

    Cost:

    All prices are charged in South African Rand (conversion is automatic).
    Total once off cost is : $99 = R1,707

    Questions?

    If you need any assistance or have questions:
    You can reply to this email
    Call or contact us on WhatsApp on +27 67 770 3960
    You can talk to us on live chat!
    Or visit our promotion directly here: https://Thao.marketing-z.cfd

发表评论

ICP证:苏ICP备15038038号-2