相关推荐recommended
nginx之location的优先级和nginx的重定向
作者:mmseoamin日期:2024-01-18

一、nginx之location的优先级和匹配方式(重点)

(一)nginx的正则表达式

nginx的正则表达式

符号

含义

^

字符串的起始位置(以什么开头)

$

字符串的结束位置(以什么结尾)

*

匹配所有

+

匹配前面的字符最少1次

?

匹配前面的字符0次或者1次

.

任意单个字符

{n}

连续重复出现n次

{n,m}

连续重复n-m次

[c]

匹配单个字符c

()

分组

|

(二)location匹配的分类:location一旦匹配成功,不再向下继续匹配

1、精确匹配:完整路径,一个字不能少,也不能错

(1)格式:location = / {}

2、正则匹配

(1)格式:location ~ / {}

正则匹配符号

含义

^~

前缀匹配,以什么为开头

~

区分大小写进行匹配

~*

不区分大小写进行匹配

!~

区分大小写取反匹配

!~*

不区分大小写取反匹配

3、一般匹配:location /test {}

(三)location匹配的优先级(重点)

1、精确匹配的优先级最高——正则匹配——一般匹配优先级最低

location = 完整路径 > location ^~ > location~/~* > location /test > location /

2、生产中配置location的原则

(1)网站首页(一般是静态页面,匹配网站的根工作目录):一律都是精确匹配

①格式:

location = / {

}

(2)处理静态文件的请求:目录匹配和后缀匹配

①格式:

location ^~ /static {

}

location ~* \. (html|jpg|jepg)$ {

}

(3)一般匹配:做反向代理、动态请求,把动态请求转发到后端的服务器

①格式:

location / {

proxy_pass http://tomcat server;

}

nginx之location的优先级和nginx的重定向,第1张

nginx之location的优先级和nginx的重定向,第2张nginx之location的优先级和nginx的重定向,第3张

nginx之location的优先级和nginx的重定向,第4张

二、nginx的重定向(页面跳转)

(一)rewrite的相关概念

1、rewrite:结合nginx提供的全局变量和自定义的变量,结合正则表达式以及标志位实现

url重写以及重定向

2、rewrite中可以添加if语句,但只有if没有else

(二)rewrite的执行顺序

1、执行server块里面的rewrite

2、执行location里面定义的rewrite

3、选定location中的rewrite

(三)rewrite的语法

格式:rewrite [flag]

1、:正则表达式

2、:跳转的内容或者路径

3、[flag]:标志位,标记

(1)last:继续匹配。本条规则匹配完成后,继续向下匹配新的location URI规则

nginx之location的优先级和nginx的重定向,第5张

nginx之location的优先级和nginx的重定向,第6张

internal redirection cycle while processing:

处理请求时发生了重写或者内部重定向循环,进入了无限循环,nginx内部循环最多可以执行10次,超过10次会报错500

nginx之location的优先级和nginx的重定向,第7张

nginx之location的优先级和nginx的重定向,第8张

(2)break:本条规则匹配完之后立即终止,页面内容变化,uri不变(用的较多)

nginx之location的优先级和nginx的重定向,第9张

nginx之location的优先级和nginx的重定向,第10张

nginx之location的优先级和nginx的重定向,第11张

(3)redirect:临时重定向(302) uri的地址会发生变

nginx之location的优先级和nginx的重定向,第12张

nginx之location的优先级和nginx的重定向,第13张

(4)permanent:永久重定向(301),uri的地址会发生变化

.* :表示匹配所有

$1 :表示捕获组,$1表示引用正则表达式的第一个捕获组

www.yyy.com/test/index.html 1.jpg

www.yyy.com/ky32/index.html 1.jpg

$1 匹配就是(.*)里的内容

nginx之location的优先级和nginx的重定向,第14张

nginx之location的优先级和nginx的重定向,第15张

(四)总结

1、表面上rewrite和location都可以跳转,但区别在于rewrite是在同一域名之内更改获取资源的路径

2、location是对路径访问控制,匹配到之后不再向下继续匹配

3、临时重定向和永久重定向(会影响搜索引擎的权重)

(1)永久重定向会加入搜索引擎的权重

(2)临时重定向不会加入搜索引擎的权重

(五)实验一:基于域名的跳转

www.yyy.com,公司业务变更,迁移到了新的域名www.benet.com代替,但是旧域名不能被废除(访问yyy可以跳转到benet,且匹配的uri不能变)

nginx之location的优先级和nginx的重定向,第16张

nginx之location的优先级和nginx的重定向,第17张

nginx之location的优先级和nginx的重定向,第18张

(六)实验二:基于ip地址的域名

公司业务新版本上线,用户访问网站统一显示固定的维护页面,只有公司的20.0.0.xx可以访问

nginx之location的优先级和nginx的重定向,第19张

nginx之location的优先级和nginx的重定向,第20张nginx之location的优先级和nginx的重定向,第21张

nginx之location的优先级和nginx的重定向,第22张nginx之location的优先级和nginx的重定向,第23张

nginx之location的优先级和nginx的重定向,第24张