Nginx的location 规则定义

location 的匹配顺序其实是“先匹配普通,再匹配正则”,原因是:正则匹配会覆盖普通匹配

( 1 )当普通 location 前面指定了“ ^~ ”,特别告诉 Nginx 本条普通 location 一旦匹配上,则不需要继续正则匹配;( 2 )当普通location 恰好严格匹配上,不是最大前缀匹配,则不再继续匹配正则。

总结一句话:  “正则 location 匹配让步普通 location 的严格精确匹配结果;但覆盖普通 location 的最大前缀匹配结果”

syntax: location [=|~|~*|^~|@] /uri/ { … }

一、匹配到了“普通location ”后,不再需要继续匹配“正则location ”了

要做到这一点只要在“普通location ”前面加上“^~ ”符号(^ 表示“非”,~ 表示“正则”,字符意思是:不要继续匹配正则)。

例如:  location ^~ /Register?

除了上文的“^~ ”可以阻止继续搜索正则location 外,你还可以加“= ”。那么如果“^~ ”和“= ”都能阻止继续搜索正则location 的话,那它们之间有什么区别呢?区别很简单,共同点是它们都能阻止继续搜索正则location ,不同点是“^~ ”依然遵守“最大前缀”匹配规则,然而“= ”不是“最大前缀”,而是必须是严格匹配(exact match )。

当“最大前缀”匹配恰好就是一个“严格精确(exact match )”匹配,照样会停止后面的搜索。

二、“location / {} ”和“location = / {} ”的区别

“location / {} ”遵守普通location 的最大前缀匹配,由于任何URI 都必然以“/ ”根开头,有点默认配置的味道,其他更specific的配置能覆盖overwrite 这个默认配置

“location = / {} ”遵守的是“严格精确匹配exact match ”,也就是只能匹配 http://host:port/ 请求,同时会禁止继续搜索正则location

Example:

location   = / {

# matches the query / only.

[ configuration A ]

}

location   / {

  # matches any query, since all queries begin with /, but regular

  # expressions and any longer conventional blocks will be

  # matched first.

[ configuration B ]

}

location ^~ /images/ {

    # matches any query beginning with /images/ and halts searching,

# so regular expressions will not be checked.

[ configuration C ]

}

location ~* \.(gif|jpg|jpeg)$ {

# matches any request ending in gif, jpg, or jpeg. However, all

# requests to the /images/ directory will be handled by

# Configuration C.

[ configuration D ]

}

三、“~ ”和“~* ”前缀

“~ ”和“~* ”前缀表示正则location ,“~ ”区分大小写,“~* ”不区分大小写

You May Also Like

About the Author: daidai5771

发表评论

电子邮件地址不会被公开。 必填项已用*标注