前言
nginxserver下配置多个location根据路径匹的不同做不同的处理。
nginx常用正则表达式
语法规则:location[=|~|~*|^~]/uri/{…}
- =开头表示:精确匹配。
- ^~开头表示:区分大小写以什么开头。
- ~开头表示:区分大小写的正则匹配。
- ~*开头表示:不区分大小写的正则匹配。
- !~和!~*分别表示:区分大小写不匹配及不区分大小写不匹配的正则匹配。
- /表示:通用匹配,任何请求都会匹配到。
多个location配置的情况下匹配顺序为(未验证):
首先匹配=,其次匹配^~,其次是按文件中顺序的正则匹配,最后是交给/通用匹配。当有匹配成功时候,停止匹配,按当前匹配规则处理请求。
实测
server{listen80;listen[::]:80;server_namelocation.test.com;access_log/var/log/nginx/location.host.access.logmain;#*********************注意多个location通常按精确的放前面,模糊大范围的放后面,nginx先找=******************************location=/login.html{#精确匹配/loginroot/usr/share/nginx/html/test-equal;#请求/login.html相当于寻找资源/usr/share/nginx/html/test-equal/login.html}location^~/prefix/{#区分大小写且以/prefix/开头root/usr/share/nginx/html/test-prefix;#root代表根目录,请求/prefix/prefix.html相当于寻找资源/usr/share/nginx/html/test-prefix/prefix/prefix.html}location~\.(png|jpg)${#不区分大小写且以.png或.jpg结尾root/usr/share/nginx/html/test-suffix;#请求/suffix/a.png相当于寻找资源/usr/share/nginx/html/test-suffix/suffix/a.png}location^~/jd/{#区分大小写且以/jd/开头proxy_passhttps://www.jd.com/;#proxy_pass此处的url以/结尾,则nginx会取掉location部分再转发,例如,请求/jd/电器?name=1则会转发到https://www.jd.com/电器?name=1}location^~/s{#/会匹配到所有的proxy_passhttps://www.百度.com;#proxy_pass此处的url没有以/结尾,则匹配到的地址全部拼接到代理后的地址,例如,请求/s?name=1则会转发到https://www.百度.com/s?name=1}location/{#会返回index.htmlroot/usr/share/nginx/html;indexindex.html;}}
备注
location下的root和alias区别:
例子:
客户端请求:http://localhost:8080/user/info/a.txt
nginx如果用root配置:nginx会去寻找资源:/home/html/user/info/a.txt
location^~/user{
root/home/html;#此处可以不以/结尾
}
nginx如果用alias配置:nginx会去寻找资源:/home/html/info/a.txt
location^~/user{
alias/home/html/;#此处以/结尾
}