来源:https://blog.csdn.net/qq_40907977/article/details/106815216 参考:https://juejin.cn/post/7048952689601806366
location 路径匹配
=
开头表示精确匹配。如 A 中只匹配根目录结尾的请求,后面不能带任何字符串;^~
开头表示uri以某个常规字符串开头,不是正则匹配;~
开头表示区分大小写的正则匹配;~*
开头表示不区分大小写的正则匹配;/
通用匹配, 如果没有其它匹配,任何请求都会匹配到。
优先级
( location = ) > ( location 完整路径 ) > ( location ^~ 路径 ) > ( location ,* 正则顺序 ) > ( location 部分起始路径 ) > ( / )
root
location中root指定的只是相对路径,需要和路径结合起来映射地址,比如
location ^~/static/ { ## 这里的root需要和路径结合使用,即是映射的文件位置为 /usr/alyingboy/static
root /usr/alyingboy/;
index index.html
}
转发规则 IP/static/a.css
-> /usr/alyingboy/static/a.css
alias
alias指定的是绝对路径,不会和location中的路径结合使用,而是直接使用地址映射到文件
location ^~/static/ { ## 不会路径结合映射地址,那么这里就会直接映射到 /usr/alyingboy/ 文件夹下的文件
alias /usr/alyingboy/;
index index.html
}
如果定义的路径是文件夹,那么需要使用 /
结尾
一旦配置请求location映射到了指定的位置,那么下面全部的文件夹和文件都可以映射到,不需要在配置对其的映射,比如 ,但是如果使用其中的文件名重新映射了地址,那么这个路径将不能使用
# /usr/alyingboy/文件夹下的全部文件包括子文件夹和文件都可以使用指定的地址访问到,比如访问地址为 :# IP/static/a.txt ,那么这个地址访问的是/usr/alyingboy/static/a.txt文件location / {
root /usr/alyingboy/;
index index.html;
}
举例
location = / {
# 精确匹配 / ,主机名后面不能带任何字符串
[ configuration A ]
}
location / {
# 因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求
# 但是正则和最长字符串会优先匹配
[ configuration B ]
}
location /documents/ { # 匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索
# 只有后面的正则表达式没有匹配到时,这一条才会采用这一条
[ configuration C ]
}
location ~ /documents/Abc { # 匹配任何以 /documents/Abc 开头的地址,匹配符合以后,还要继续往下搜索
# 只有后面的正则表达式没有匹配到时,这一条才会采用这一条
[ configuration CC ]
}
location ^~ /images/ { # 匹配任何以 /images/ 开头的地址,匹配符合以后,停止往下搜索正则,采用这一条。
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ { # 匹配所有以 gif,jpg或jpeg 结尾的请求
# 然而,所有请求 /images/ 下的图片会被 config D 处理,因为 ^~ 到达不了这一条正则
[ configuration E ]
}
location /images/ { # 字符匹配到 /images/,继续往下,会发现 ^~ 存在
[ configuration F ]
}
location /images/abc { # 最长字符匹配到 /images/abc,继续往下,会发现 ^~ 存在
# F与G的放置顺序是没有关系的
[ configuration G ]
}
location ~ /images/abc/ { # 只有去掉 config D 才有效:先最长匹配 config G 开头的地址,继续往下搜索,匹配到这一条正则,采用
# 因为都是正则匹配,优先级一样,选择最上面的
[ configuration H ]
}
location ~* ^/(api/v1/users|admin/v2/settings) {
# 这里是你的配置
}
location ~* /js/.*/\.js
proxy_pass
第一种
location /proxy/ {
proxy_pass http://127.0.0.1/;
}
代理到URL:http://127.0.0.1/test.html
第二种(相对于第一种,最后少一个 / )
location /proxy/ {
proxy_pass http://127.0.0.1;
}
代理到URL:http://127.0.0.1/proxy/test.html
第三种
location /proxy/ {
proxy_pass http://127.0.0.1/aaa/;
}```
代理到URL:http://127.0.0.1/aaa/test.html
### 第四种(相对于第三种,最后少一个 / )
location /proxy/ { proxy_pass http://127.0.0.1/aaa; } ``` 代理到URL:http://127.0.0.1/aaatest.html