Nginx的location的优先级和匹配方式:
在http模块有server,在server模块才有location,location匹配的是uri
在一个server当中有多个location,如何来确定匹配哪个location
location匹配的分类:
精确匹配
location = /test {..}
完整路径一个字都不能少,也不能错
www.ky32.com/test
正则匹配
location ~ / {}
location^~:前缀匹配,以什么开头
~:区分大小写进行匹配
~*:不区分大小写进行匹配
!~:区分大小写取反匹配
!~*:不区分大小写取反匹配
一般匹配
location /test {}
location匹配一旦匹配成功,不再向下匹配
精确匹配优先级最高——其次是正则匹配——一般匹配
location = 完整路径 > location ^~ > location ~,~* > location /test > location /
工作当中配置location的原则:
网站首页:都是精确匹配 一般情况下网站首页都是一个静态页面
location = / {
}
处理静态文件的请求:目录匹配和后缀匹配
location ^~ /static {
}
location ~* \. {html|jpg|jpeg|gif|png} $ {
}
一般规则:动态请求,把动态请求转发的后端的动态页面的服务器
location / {
proxy_pass http://tomcat server;
}
nginx的重定向:
rewrite:结合nginx提供的全局变量和自定义的变量,结合正则表达式以及标志位实现url重写以及重定向。
rewrite执行顺序:
- 执行server块里面的rewrite
- 执行location里面定义的rewrite
- 选定location中的rewrite
rewrite中可以if语句,只有if没有else
rewrite:
Rewrite <regex> <replacemnet> [flag]
<regex>:正则表达式
<replacemnet>:跳转的内容或者路径
[flag}:标志位 “标记”
flag:
last:本条规则匹配完成后,继续向下匹配新的location URI规则
location / {
rott html
rewrite last
}
break:本条规则匹配完之后立即终止,页面内容变化,uri不变
redirct:临时重定向302 uri的地址会发生变化
permanent:永久重定向301 uri的地址会发生变化
rewrite /test/(.*) /ky32/$1 permanent;
.*:匹配所有
$1:表示捕获组$1 引用正则表达式的第一个捕获组
搜索引擎的权重
永久重定向会加入搜索引擎的排名
临时不会加入搜索引擎的权重
last:继续匹配
总结:rewrite和location都可以跳转,似乎有点相同,但是区别在于rewrite是在同一域名之内更改获取资源的路径,location是对路径访问控制。
基于ip访问跳转:
公司业务新版本上线,用户访问网站统一显示固定的维护页面
只有公司的192.168.233.61可以访问。