nginx location配置

nginx虚拟主机配置中,我们通过虚拟主机可以实现不同域名不同端口,访问不同的资源文件。在域名和端口相同时,可以通过location配置实,现用户访问不同url,返回不同的资源文件。常用于实现动静分离等。
nginx.conf 中默认配置如下

location / {
     root  html;
     index index.html index.htm;
   }

配置语法

location [= | ~* | ^~ ] /uri/ {...}

配置规则
location = /uri {} 精准匹配
location ^~ /uri {} 前缀匹配 以xx开头
location ~ /uri {} 区分大小写 以xx结尾
location ~* /uri {} 不区分大小写 以xx结尾
location !~ /uri {} 区分大小写 不以xx结尾
location !~* /uri {} 不区分大小 不以xx结尾
location / 通用匹配 (nginx.conf中的默认配置)

优先级
一个server中可以配置多个location 不同location 有优先级如下:

  1. 精准匹配是优先级最高
  2. ^~以xx开头的匹配(多个规则满足时 匹配 长度最长的)
  3. 文件中顺序的正则匹配 (第一个匹配上的)
  4. 通用匹配

验证:

对nginx.conf 中的一台虚拟主机 配置 location 如下每个location对应的根目录不同 :

   server {
    listen       8080;
    server_name  localhost;
    #charset koi8-r;
    #access_log  logs/host.access.log  main;
    location = / {
        root   html/1;
        index  index.html;
    }
    location = /index.txt {
        root   html/2;
        index  index.html;
    }
    location ^~ /articles/ {
        root   html/3;
        index  index.html;
    }
    location ^~ /articles/files/ {
        root   html/4;
        index  index.html;
    }
    location / {
        root   html;
        index  8080.html 8080.htm;
    }
}

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 同理

[root@zk03 html]# ll
总用量 20
drwxr-xr-x. 3 root root  66 1月  23 16:43 1
drwxr-xr-x. 3 root root  66 1月  23 16:43 2
drwxr-xr-x. 3 root root  66 1月  23 16:43 3
drwxr-xr-x. 3 root root  66 1月  23 16:43 4
drwxr-xr-x. 3 root root  66 1月  23 16:43 5

nginx重新加载配置文件

./sbin/nginx -s reload

分别访问如下url进行测试,访问到的界面结果如下

http://zk03:8080/index.txt 走了第二个规则 如下:
在这里插入图片描述

http://zk03:8080/articles/files/1.txt 走了第四个规则 如下:
在这里插入图片描述

其他这里不做验证了

疑问: zk03:8080/ 竟然返回了默认 index 按理说应该走1啊
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

catch that elf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值