location 语法php
location 有”定位”的意思, 根据Uri来进行不一样的定位.html
在虚拟主机的配置中,是必不可少的,location能够把网站的不一样部分,定位到不一样的处理方式上.nginx
好比, 碰到.php, 如何调用PHP解释器? --这时就须要location正则表达式
location 的语法ide
location [=|~|~*|^~] patt {测试
}网站
中括号能够不写任何参数,此时称为通常匹配url
也能够写参数spa
所以,大类型能够分为3种server
location = patt {} [精准匹配]
location patt{} [通常匹配]
location ~ patt{} [正则匹配]
如何发挥做用?:
首先看有没有精准匹配,若是有,则中止匹配过程.
location = patt {
config A
}
若是 $uri == patt,匹配成功,使用configA
location = / {
root /var/www/html/;
index index.htm index.html;
}
(=/精准匹配到/,可是,这是个目录,index会去找文件,先找index.htm,没有就找index.html。若是index.html也没有,就走下一个location)
location / {
root /usr/local/nginx/html;
index index.html index.htm;
}
(先匹配精确匹配=/,不行再匹配/)
上面的配置分析:
若是访问 http://xxx.com/
定位流程是
1: 精准匹配中 ”/” ,获得index页为 index.htm
2: 再次访问 /index.htm , 这次内部转跳uri已是”/index.htm” ,
根目录为/usr/local/nginx/html
3: 最终结果,访问了 /usr/local/nginx/html/index.htm
上面的例子若是改一下,改为准确到文件的精确访问:
若访问/,先去location =/,匹配/index.html,如有,就是/index.html,走location =/ index.html
再来看,正则也来参与.
location / {
root /usr/local/nginx/html;
index index.html index.htm;
}
location ~ image {
root /var/www/image;
index index.html;
}
若是咱们访问 http://xx.com/image/logo.png
此时, “/” 与”/image/logo.png” 匹配
同时,”image”正则 与”image/logo.png”也能匹配,谁发挥做用?
正则表达式的成果将会使用.
图片真正会访问 /var/www/image/logo.png
location / {
root /usr/local/nginx/html;
index index.html index.htm;
}
location /foo {
root /var/www/html;
index index.html;
}
咱们访问 http://xxx.com/foo
对于uri “/foo”, 两个location的patt,都能匹配他们
即 ‘/’能从左前缀匹配 ‘/foo’, ‘/foo’也能左前缀匹配’/foo’,
此时, 真正访问 /var/www/html/index.html
缘由:’/foo’匹配的更长,所以使用之.;
location [ = | ~ | ~* | ^~ ] uri { ... }
在一个server中location配置段可存在多个,用于实现从uri到文件系统的路径映射;ngnix会根据用户请求的URI来检查定义的全部location,并找出一个最佳匹配,然后应用其配置;
=:对URI作精确匹配;例如, http://www.magedu.com/, http://www.magedu.com/index.html
location = / {
...
}
~:对URI作正则表达式模式匹配,区分字符大小写;
~*:对URI作正则表达式模式匹配,不区分字符大小写;
^~:对URI的左半部分作匹配检查,不区分字符大小写;
不带符号:匹配起始于此uri的全部的url;
匹配优先级:=, ^~, ~/~*,不带符号;
= 严格匹配。若是这个查询匹配,那么将中止搜索并当即处理此请求。
~ 为区分大小写匹配(可用正则表达式)
!~为区分大小写不匹配
~* 为不区分大小写匹配(可用正则表达式)
!~*为不区分大小写不匹配
^~ 若是把这个前缀用于一个常规字符串,那么告诉nginx 若是路径匹配那么不测试正则表达式。
location ^~ /images/ {
# 匹配任何以 /images/ 开头的任何查询而且中止搜索。任何正则表达式将不会被测试。
}