引言
当我们在用nginx做路径映射的时候 有很多时候都会吃碰到 location的正则匹配问题和 proxy_pass,今天就讲述一下这两点
location的正则匹配
当我们使用location做正则匹配的时候,如果location过多的时候,我们首先要看location执行的优先级,考虑还需不惜要继续往下执行。
(location =) > (location 完整路径) > (location ^~ 路径) > (location ~,~* 正则顺序) > (location 部分起始路径) > (/)
常用nginx正则
* 代表任意字符
~ 区分大小写匹配
~* 不区分大小写匹配
!~和!~*分别为区分大小写不匹配及不区分大小写不匹配
^ 以什么开头的匹配
$ 以什么结尾的匹配
栗子
匹配任何已/images/开头的任何查询并且停止搜索。
location ^~ /images/ {
}
匹配任何已.gif、.jpg 或 .jpeg 结尾的请求
location ~* .(gif|jpg|jpeg)$ {
}
配置proxy_pass
大家在nginx中配置proxy_pass时,如果是按照^~匹配路径时,
要注意proxy_pass后的url最后的/,当加上了/,相当于是绝对根路径,
则nginx不会把location中匹配的路径部分代理走,如果没有/,则会把匹配的路径部分也给代理走。
栗子
location ^~ /static_js/ {
proxy_cache js_cache;
proxy_set_header Host js.test.com;
proxy_pass http://nav.xiangjv.top/;
}
# 上面这段 如果我们请求的路径是 http://xiangjv.top/servername/static_js/test.html
# 会被代理成http://nav.xiangjv.top/test.html
# 如果不加 / proxy_pass http://nav.xiangjv.top;
# 同样的路径 会被代理到 http://nav.xiangjv.top/servername/static_js/test.html
# 这样也就达到了我们要求的完整映射
这个”/”,令到出来的结果完全不同
PS: 如果是 location ~* ^/start/(.*).html 这种正则的location,是不能写”/”上去的,nginx -t 也会报错的了。因为,路径都需要正则匹配了嘛,并不是一个相对固定的locatin了,必然要代理到一个server。
标签: 服务器nginx前端front