岳阳建设网站制作,杭州市网站seo,dw做的上传网站打不开,美管加登录平台Nginx 的 rewrite 指令用于根据正则表达式来匹配请求的 URI#xff0c;并将其重写为新的 URI。rewrite 指令可以包含一个可选的 flag#xff08;标志#xff09;#xff0c;该标志用于控制重写操作后的行为。
rewrite regex replacement [flag]
一. 常用四种 flag
redir…Nginx 的 rewrite 指令用于根据正则表达式来匹配请求的 URI并将其重写为新的 URI。rewrite 指令可以包含一个可选的 flag标志该标志用于控制重写操作后的行为。
rewrite regex replacement [flag]
一. 常用四种 flag
redirect302 临时重定向
当重写完成后以临时重定向的方式返回重写后生成的新 URL给客户端状态码为 302。浏览器地址栏会显示跳转后的 URL 地址。
permanent301 永久重定向
当重写完成后以永久重定向的方式返回重写后生成的新 URL 给客户端状态码为 301。浏览器地址栏会显示跳转后的 URL 地址。
break
重写完成后停止对当前 URL 在当前 location 以及其他 location 中当前 serve后续的其它重写操作。不会跳出 location 作用域也不会重新搜索与更改后的 URI 相匹配的 location。适用于一个 URL 一次重写的场景。
last
重写完成后停止对当前 URI 在当前 location 中后续的其它重写操作。但会对新的 URL 启动新一轮重写检查并可能跳出当前 location 作用域搜索与更改后的 URI 相匹配的 location。适用于一个 URL 可能需要多次重写的场景。
二. last 和 break 区别
server {listen 80;server_name pic.path-analytics.com;root /tmp/html/;location / {rewrite /1.html /2.html;rewrite /2.html /3.html;}location /2.html {rewrite /2.html /a.html;}location /3.html {rewrite /3.html /b.html;}
}情况一无 flag
访问 http://pic.path-analytics.com/1.html结果为 执行顺序如下 首先匹配 location 然后根据第一个 rewrite 将 URL 由 /1.html 改写为了 /2.html 此时并未重新发起请求而是在当前 location 中查找是否有关于 /2.html 的 重写规则 查找到第二个 rewrite 将 URL 由 /2.html 改写成 /3.html再去查找当前 locaiton 中是否还有 /3.html 的重写规则 没有找到此时 URL 为 http://pic.path-analytics.com/3.html 再次去请求匹配 location 进入该 location将 URL 由 /3.html 改写为 /b.html。这个 location 中没有 /b.html 的改写规则此时 URL 为 http://pic.path-analytics.com/b.html 再次去请求匹配 location 但是该 location 中没有 /b.html 的匹配规则所以直接响应 b.html
情况二break
location / {rewrite /1.html /2.html break;rewrite /2.html /3.html;
}访问 http://pic.path-analytics.com/1.html结果为 执行顺序如下
首先匹配 location 执行第一个 rewrite 将 URL 由 /1.html 改写为 /2.htmlbreak 直接终止了当前 location 和其他 location 的匹配返回 2.html
情况三last
location / {rewrite /1.html /2.html last;rewrite /2.html /3.html;
}访问 http://pic.path-analytics.com/1.html结果为 执行顺序如下
首先匹配 location 执行第一个 rewrite 将 URL 由 /1.html 改写为 /2.htmllast 终止了当前 location 中的匹配此时 URL 为 http://pic.path-analytics.com/2.html再次去请求匹配 location 根据 rewrite 将 URL 由 /2.html 改写为 /a.html此时 URL 为 http://pic.path-analytics.com/a.html再次去请求匹配 location 该 location 中没有 /a.html 的匹配规则所以直接响应 a.html
情况四修改 location 优先级
在 location 中使用正则匹配
location ~ / {rewrite /1.html /2.html last;rewrite /2.html /3.html;
}访问 http://pic.path-analytics.com/1.html结果为 执行顺序如下
首先去匹配 location 根据第一个 rewrite 将 URL 由 /1.html 改写为 /2.htmllast 终止了当前 location 中的匹配此时 URL 为 http://pic.path-analytics.com/2.html再次去请求由于 location 中正则匹配的优先级高于普通匹配匹配 location 在该 location 中根据 rewrite 将 URL 由 /2.html 改写为 /3.html此时 URL 为 http://pic.path-analytics.com/3.html再次去请求由于 location 中正则匹配的优先级高于普通匹配匹配 location 在该 location 中没有找到 /3.html 的重写规则所以直接响应 3.html
三. 不同 flag 下浏览器与网络请求的不同表现
location / {rewrite /1.html /2.html [flag];rewrite /2.html /3.html;
}location /2.html {rewrite /2.html /a.html;
}情况一没有 flag 情况二break 情况三last 情况四redirect 情况五permanent