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​​ 走了第二个规则 如下:

nginx location配置_优先级

​​http://zk03:8080/articles/files/1.txt​​ 走了第四个规则 如下:

nginx location配置_配置规则_02

其他这里不做验证了

疑问: zk03:8080/ 竟然返回了默认 index 按理说应该走1啊

nginx location配置_nginx_03