nginx配置
今天工作的时候涉及到一个内网的接口隐射到外网接口的问题,正好就记录一下
location正则写法
1 | location = / { |
- 已
=
开头表示精确匹配
如 A 中只匹配根目录结尾的请求,后面不能带任何字符串。 ^~
开头表示uri以某个常规字符串开头,不是正则匹配- b
~
开头表示区分大小写的正则匹配; ~*
开头表示不区分大小写的正则匹配/
通用匹配, 如果没有其它匹配,任何请求都会匹配到
顺序 no优先级:
(location =) > (location 完整路径) > (location ^~ 路径) > (location ~,~* 正则顺序) > (location 部分起始路径) > (/)
上面的匹配结果
按照上面的location写法,以下的匹配示例成立:
- / -> config A
精确完全匹配,即使/index.html也匹配不了 - /downloads/download.html -> config B
匹配B以后,往下没有任何匹配,采用B - /images/1.gif -> configuration D
匹配到F,往下匹配到D,停止往下 - /images/abc/def -> config D
最长匹配到G,往下匹配D,停止往下
你可以看到 任何以/images/开头的都会匹配到D并停止,FG写在这里是没有任何意义的,H是永远轮不到的,这里只是为了说明匹配顺序 - /documents/document.html -> config C
匹配到C,往下没有任何匹配,采用C - /documents/1.jpg -> configuration E
匹配到C,往下正则匹配到E - /documents/Abc.jpg -> config CC
最长匹配到C,往下正则顺序匹配到CC,不会往下到E
所以实际使用中,个人觉得至少有三个匹配规则定义,如下:
1 |
|
http://tengine.taobao.org/book/chapter_02.html
http://nginx.org/en/docs/http/ngx_http_rewrite_module.html
proxy_pass详解
在nginx中配置proxy_pass代理转发时,如果在proxy_pass后面的url加/,表示绝对根路径;如果没有/,表示相对路径,把匹配的路径部分也给代理走。
假设下面四种情况分别用 http://192.168.1.1/proxy/test.html 进行访问。
第一种:1
2
3
4location /proxy/ {
proxy_pass http://127.0.0.1/;
}
# 代理到URL:http://127.0.0.1/test.html
第二种(相对于第一种,最后少一个 / )1
2
3
4location /proxy/ {
proxy_pass http://127.0.0.1;
}
# 代理到URL:http://127.0.0.1/proxy/test.html
第三种:
1 | location /proxy/ { |
第四种(相对于第三种,最后少一个 / )1
2
3
4location /proxy/ {
proxy_pass http://127.0.0.1/aaa;
}
代理到URL:http://127.0.0.1/aaatest.html
参考链接
来源:Sean’s Notes
原文: http://seanlook.com/2015/05/17/nginx-location-rewrite/