nginx rewrite语法
rewrite regex replacement [flag];
- regex: 是 PCRE 语法格局的正则表达式,用于匹配字符串。
- replacement: 是重写 URI 的改写规定。当改写规定以"http://""https://"或"$scheme"结尾时,Nginx 重写该语句后将进行执行后续工作,并将改写后的 URI 跳转返回客户端。
flag: 是执行该条重写指令后的操作控制符。操作控制符有如下 4 种:
- break: 执行完以后重写规定跳转到新的 URI 后不再执行后续操作。不影响用户浏览器 URI 显示。
- last: 执行完以后重写规定跳转到新的 URI 后继续执行后续操作。
- redirect: 返回响应状态码 302 的长期重定向,返回内容是重定向 URI 的内容,但浏览器网址仍为申请时的 URI;
返回响应状态码 301 的永恒重定向,返回内容是重定向 URI 的内容,浏览器网址变为重定向的 URI。
上面一个例子将本地63561代理到nginx代理80端口上,并且所有URL上增加/prefix
前缀。location /prefix/ { rewrite ^/prefix/(.*)$ /$1 break; proxy_pass http://localhost:63561; }
原来URL http://localhost:63561/aaa => localhost/prefix/aaa
尽管在nginx增加了如下配置,可不肯定失效哦,这里就要讲下nginx URI 匹配规定URI 匹配规定
location Modifier pattern { ... }
Modifier为location的修饰语,定义URI的匹配规定。pattern 为匹配项,能够是字符串或正则表达式
没有修饰符: 从指定模式开始,只反对字符串
location /abc{
root text;
}
上面规定都匹配:
http://localhost/abc/sdssd
http://localhost/abc?page=1&s...
http://localhost/abcd
http://localhost/abc/
=
: 齐全匹配 URI 中除拜访参数以外的内容,Linux 零碎下会辨别大小写,Windows 零碎下则不会。location = /test {
root text;
}
上面都匹配
http://localhost/test
http://localhost/test?page=1&...
不匹配
http://localhost/test2ds
http://localhost/test/
~
: 辨别大小写的正则匹配location ~ /abc$ {
root text;
}
上面都匹配
http://localhost/abc
http://localhost/abc?p=123
不匹配
http://localhost/abc/
http://localhost/ABC
http://localhost/abc/bbd
~*
: 不辨别大小的正则匹配location ~* /abc$ {
root text;
}
上面都匹配
http://localhost/abc
http://localhsot/ABC
http://localhost/abc?p=123
不匹配
http://localhost/abc/
http://localhost/abc/bbd
^~
: 作用相似没有修饰符的前缀匹配,nginx对一个申请准确前缀匹配胜利后,进行持续搜寻其余到匹配项,反对正则表达式。location ^~ /abc {
root text;
}@
: 只能外部拜访的 location 区域,能够被其余外部跳转指令应用location @images {
proxy_pass http://images;
}
匹配程序
- 先检测匹配项的内容为非正则表达式修饰语的 location,而后再检测匹配项的内容为正则表达式修饰语的 location。
- 匹配项的内容为正则与非正则都匹配的 location,依照匹配项的内容为正则匹配的 location 执行。
- 所有匹配项的内容均为非正则表达式的 location,依照匹配项的内容齐全匹配的内容长短进行匹配,即匹配内容多的 location 被执行。
- 所有匹配项的内容均为正则表达式的 location,依照书写的先后顺序进行匹配,匹配后就执行,不再做后续检测。
https://www.w3schools.cn/ngin...