nginx虚拟主机配置中,我们通过虚拟主机可以实现不同域名不同端口,访问不同的资源文件。在域名和端口相同时,可以通过location配置实,现用户访问不同url,返回不同的资源文件。常用于实现动静分离等。
nginx.conf 中默认配置如下
配置语法
配置规则
location = /uri {} 精准匹配
location ^~ /uri {} 前缀匹配 以xx开头
location ~ /uri {} 区分大小写 以xx结尾
location ~* /uri {} 不区分大小写 以xx结尾
location !~ /uri {} 区分大小写 不以xx结尾
location !~* /uri {} 不区分大小 不以xx结尾
location / 通用匹配 (nginx.conf中的默认配置)
优先级
一个server中可以配置多个location 不同location 有优先级如下:
- 精准匹配是优先级最高
- ^~以xx开头的匹配(多个规则满足时 匹配 长度最长的)
- 文件中顺序的正则匹配 (第一个匹配上的)
- 通用匹配
验证:
对nginx.conf 中的一台虚拟主机 配置 location 如下每个location对应的根目录不同 :
html 目录中 创建 1、2、3、4 四个目录 每个目录中都包含 index.html index.txt 和 articles/files/1.txt 并且 文件内容 和目录名保持一致。比如 1目录下 的index.txt index.html 文件和 articles/files/1.txt 内容都是1 2目录下 的index.txt index.html 文件和 articles/files/1.txt 内容都是 2 目录 3. 和 4 同理
nginx重新加载配置文件
分别访问如下url进行测试,访问到的界面结果如下
http://zk03:8080/index.txt 走了第二个规则 如下:
http://zk03:8080/articles/files/1.txt 走了第四个规则 如下:
其他这里不做验证了
疑问: zk03:8080/ 竟然返回了默认 index 按理说应该走1啊