项目中需要使用内部接口,要在 nginx 层面上禁止外部的访问
location 修饰符类型
>>【 = 】:修饰符:要求路径完全匹配
server {
server_name website.com;
location = /abcd {
[…]
}
}
-
http://website.com/abcd
匹配 -
http://website.com/ABCD
可能会匹配 ,也可以不匹配,取决于操作系统的文件系统是否大小写敏感(case-sensitive)。ps: Mac 默认是大小写不敏感的,git 使用会有大坑。 -
http://website.com/abcd?param1¶m2
匹配,忽略 querystring -
http://website.com/abcd/
不匹配,带有结尾的` -
http://website.com/abcde
不匹配
>>【 ~ 】修饰符:区分大小写的正则匹配
server {
server_name website.com;
location ~ ^/abcd$ {
[…]
}
}
^/abcd
‘
这
个
正
则
表
达
式
表
示
字
符
串
必
须
以
‘
/
‘
开
始
,
以
‘
`这个正则表达式表示字符串必须以`/`开始,以`
‘这个正则表达式表示字符串必须以‘/‘开始,以‘结束,中间必须是
abcd
http://website.com/abcd
匹配(完全匹配)http://website.com/ABCD
不匹配,大小写敏感http://website.com/abcd?param1¶m2
匹配http://website.com/abcd/
不匹配,不能匹配正则表达式http://website.com/abcde
不匹配,不能匹配正则表达式
>> 【 ~* 】不区分大小写的正则匹配
server {
server_name website.com;
location ~* ^/abcd$ {
[…]
}
}
-
http://website.com/abcd
匹配 (完全匹配) -
http://website.com/ABCD
匹配 (大小写不敏感) -
http://website.com/abcd?param1¶m2
匹配 -
http://website.com/abcd/
不匹配
,不能匹配正则表达式 -
http://website.com/abcde
不匹配
,不能匹配正则表达式
总结
- =开头表示精确匹配
- ^~ 开头表示uri以某个常规字符串开头,这个不是正则表达式
- ~ 开头表示区分大小写的正则匹配;
- ~* 开头表示不区分大小写的正则匹配
- / 通用匹配, 如果没有其它匹配,任何请求都会匹配到
优先级
(location =) > (location 完整路径) > (location ^~ 路径) > (location ,* 正则顺序) > (location 部分起始路径) > (/)
结果
#内部接口,禁止访问
location ~* /api/\S+/inner {
deny all;
}
\S
: 匹配任何非空白字符。+
: 匹配前面的子表达式一次或多次。要匹配 + 字符,请使用 +。
注:数字可以被识别为字符
2020-08-14 新增
由于 项目的文件系统变更,minio作为新的分布式文件系统,所以nginx原来的转发策略需要修改。
Nginx 配置 proxy_pass 转发的 / 路径问题
在 nginx 中配置 proxy_pass 时,如果是按照 ^~ 匹配路径时,要注意 proxy_pass 后的url 最后的 / ,当加上 / 就相当于绝对路径,则 nginx 不会把 location 中匹配的路径也转发;
如果没有 / ,则会把匹配的路径部分也给代理走。
举个栗子就能就能理解了:
location ^~ /request/
{
proxy_pass http://server.com/;
}
如果是上面的配置,假如请求的 url 是:http://xxx/request/test.html
则会被代理成: http://server.com/test.html (也就是 request 会被过滤)
反之,proxy_pass 的url 最后没有加 /,
则会被代理成: http://server.com/request/test.html (也就是 request 没有被过滤)