nginx程序区域模块 - location
功能:匹配不同的uri信息,做出相应处理
Syntax: location [ = | ~ | ~* | ^~ ] uri { ... } 语法结构
匹配 uri 执行什么动作
awk '模式{动作}'
Default: —
Context:server, location --- 可以配置在什么区域中
=: 精确匹配 = /oldboy www.oldboy.com /oldboy
~: 模糊匹配(区分大小写)
~*: 模糊匹配(不区分大小写)
^~: 优先匹配 不识别uri信息中正则符号
/: 默认匹配
如何应用:
location = / { 01
return 301;
}
location / { 05 默认匹配
return 302;
}
location /documents/ { 04
return 404;
}
location ^~ /images/ { 02
return 502;
}
location ~* .(gif|jpg|jpeg)$ { 03
return 520;
}
样例:测试 ~ 和 ~*
location ~ /test/ {
return 301;
}
location ~* /test/ {
return 302;
}
规范站点目录结构信息:
[root@web01 conf.d]# cat www.conf
server {
listen 80;
server_name www.oldboy.com;
location ~* .jpg$ {
root /html/www/jpg;
}
location ~* .png$ {
root /html/www/png;
}
location / {
root /html;
index index.html;
}
}
location /web/ /web 的区别
server {
listen 80;
server_name proxy_cache.yangyijing.cn;
location /web {
proxy_pass http://cache;
proxy_cache code_cache;
include proxy_params;
}
}
/web/ 的功能是精准匹配
/web 的功能是模糊匹配 可以匹配/webbbbsf 就是/web* 任意字符
proxy_pass有无“/”的四种区别探究
访问地址都是以:http://www.wandouduoduo.com/wddd/index.html 为例。请求都匹配目录/wddd/
第一种:加"/"
location /wddd/ {
proxy_pass http://127.0.0.1:8080/;
}
测试结果,请求被代理跳转到:http://127.0.0.1:8080/index.html
第二种: 不加"/"
location /wddd/ {
proxy_pass http://127.0.0.1:8080;
}
测试结果,请求被代理跳转到:http://127.0.0.1:8080/wddd/index.html
第三种: 增加目录加"/"
location /wddd/ {
proxy_pass http://127.0.0.1:8080/sun/;
}
测试结果,请求被代理跳转到:http://127.0.0.1:8080/sun/index.html
第四种:增加目录不加"/"
location /wddd/ {
proxy_pass http://127.0.0.1:8080/sun;
}
测试结果,请求被代理跳转到:http://127.0.0.1:8080/sun/index.html
总结
location目录后加"/",只能匹配目录,不加“/”不仅可以匹配目录还对目录进行模糊匹配。而proxy_pass无论加不加“/”,代理跳转地址都直接拼接。为了加深大家印象可以用下面的配置实验测试下:
server {
listen 80;
server_name localhost; # http://localhost/wddd01/xxx -> http://localhost:8080/wddd01/xxx
location /wddd01/ {
proxy_pass http://localhost:8080;
}
# http://localhost/wddd02/xxx -> http://localhost:8080/xxx
location /wddd02/ {
proxy_pass http://localhost:8080/;
}
# http://localhost/wddd03/xxx -> http://localhost:8080/wddd03*/xxx
location /wddd03 {
proxy_pass http://localhost:8080;
}
# http://localhost/wddd04/xxx -> http://localhost:8080//xxx,请注意这里的双斜线,好好分析一下。
location /wddd04 {
proxy_pass http://localhost:8080/;
}
# http://localhost/wddd05/xxx -> http://localhost:8080/hahaxxx,请注意这里的haha和xxx之间没有斜杠,分析一下原因。
location /wddd05/ {
proxy_pass http://localhost:8080/haha;
}
# http://localhost/api6/xxx -> http://localhost:8080/haha/xxx
location /wddd06/ {
proxy_pass http://localhost:8080/haha/;
}
# http://localhost/wddd07/xxx -> http://localhost:8080/haha/xxx
location /wddd07 {
proxy_pass http://localhost:8080/haha;
}
# http://localhost/wddd08/xxx -> http://localhost:8080/haha//xxx,请注意这里的双斜杠。
location /wddd08 {
proxy_pass http://localhost:8080/haha/;
}
}