nginx中location配置说明
2017-09-01 17:25
197 查看
location匹配顺序
"="前缀指令匹配,如果匹配成功,则停止其他匹配普通字符串指令匹配,顺序是从长到短,匹配成功的location如果使用^~,则停止其他匹配(正则匹配)
正则表达式指令匹配,按照配置文件里的顺序,成功就停止其他匹配
如果第三步中有匹配成功,则使用该结果,否则使用第二步结果
注意点
匹配的顺序是先匹配普通字符串,然后再匹配正则表达式。另外普通字符串匹配顺序是根据配置中字符长度从长到短,也就是说使用普通字符串配置的location顺序是无关紧要的,反正最后nginx会根据配置的长短来进行匹配,但是需要注意的是正则表达式按照配置文件里的顺序测试。找到第一个比配的正则表达式将停止搜索。一般情况下,匹配成功了普通字符串location后还会进行正则表达式location匹配。有两种方法改变这种行为,其一就是使用“=”前缀,这时执行的是严格匹配,并且匹配成功后立即停止其他匹配,同时处理这个请求;另外一种就是使用“^~”前缀,如果把这个前缀用于一个常规字符串那么告诉nginx 如果路径匹配那么不测试正则表达式。
匹配模式及顺序
location = /uri =开头表示精确匹配,只有完全匹配上才能生效。location ^~ /uri ^~ 开头对URL路径进行前缀匹配,并且在正则之前。
location ~ pattern ~开头表示区分大小写的正则匹配。
location ~* pattern ~*开头表示不区分大小写的正则匹配。
location /uri 不带任何修饰符,也表示前缀匹配,但是在正则匹配之后。
location / 通用匹配,任何未匹配到其它location的请求都会匹配到,相当于switch中的default。
实验案例
测试"^~"和"~",nginx配置如下。浏览器输入http://localhost/helloworld/test,返回601。如将#1注释,#2打开,浏览器输入http://localhost/helloworld/test,返回603。注:#1和#2不能同时打开,如同时打开,启动nginx会报nginx: [emerg] duplicate location "/helloworld"...,因为这两个都是普通字符串。location ^~ /helloworld { #1 return 601; } #location /helloworld { #2 # return 602; #} location ~ /helloworld { return 603; }
测试普通字符串的长短(普通字符串的匹配与顺序无关,与长短有关)。浏览器输入http://localhost/helloworld/test/a.html,返回601。浏览器输入http://localhost/helloworld/a.html,返回602。
location /helloworld/test/ { #1 return 601; } location /helloworld/ { #2 return 602; }
测试正则表达式的顺序(正则匹配与顺序相关)。浏览器输入http://localhost/helloworld/test/a.html,返回602;将#2和#3调换顺序,浏览器输入http://localhost/helloworld/test/a.html,返回603
location /helloworld/test/ { #1 return 601; } location ~ /helloworld { #2 return 602; } location ~ /helloworld/test { #3 return 603;
相关文章推荐
- Nginx中ip_hash负载均衡中location的proxy_pass配置与说明
- nginx location 配置阐述优先级别使用说明
- nginx location 配置阐述优先级别使用说明
- nginx location 配置阐述优先级别使用说明-不当可能存在安全隐患
- nginx配置文件中location说明
- Nginx中ip_hash负载均衡中location的proxy_pass配置与说明
- Nginx—核心配置location匹配规则说明
- nginx的location配置
- nginx 反向代理 配置 https 实现http https同时存在 经测试 支持location 规则
- Nginx配置文件详细说明
- Nginx 完整配置说明
- Nginx配置指令location匹配符优先级和安全问题
- nginx 配置说明及优化
- nginx配置说明
- Nginx 完整配置说明
- Ngin的配置文件nginx.conf完整配置说明(包括fastcgi和负载均衡设置)
- nginx相关配置说明
- Nginx配置文件的常用设置(附详细说明及Nginx的proxy负载均衡、memcached负载均衡、反向代理)
- Nginx配置文件详细说明
- Nginx配置文件详细说明