nginx location指令详解
  0GY0ciDQP24T 2023年11月02日 42 0

nginx location指令详解_html

Nginx的HTTP配置主要包括三个区块,结构如下:
http { //这个是协议级别
  include mime.types;
  default_type application/octet-stream;
  keepalive_timeout 65;
  gzip on;
    server { //这个是服务器级别
      listen 80;
      server_name localhost;
        location / { //这个是请求级别
          root html;
          index index.html index.htm;
        }
      }
}

nginx location指令详解_html

location区段

通过指定模式来与客户端请求的URI相匹配,基本语法如下:location [=|~|~*|^~|@] pattern{……}

1、没有修饰符 表示:必须以指定模式开始,如:

nginx location指令详解_html

server {
  server_name baidu.com;
  location /abc {
    ……
  }
}

那么,如下是对的:
​​​http://baidu.com/abc​​​http://baidu.com/abc?p1
http://baidu.com/abc/
http://baidu.com/abcde

nginx location指令详解_html

 

2、=表示:必须与指定的模式精确匹配

nginx location指令详解_html

server {
server_name sish
  location = /abc {
    ……
  }
}
那么,如下是对的:
http://baidu.com/abc
http://baidu.com/abc?p1
如下是错的:
http://baidu.com/abc/
http://baidu.com/abcde

nginx location指令详解_html

 

3、~ 表示:指定的正则表达式要区分大小写

nginx location指令详解_html

server {
server_name baidu.com;
  location ~ ^/abc$ {
    ……
  }
}
那么,如下是对的:
http://baidu.com/abc
http://baidu.com/abc?p1=11&p2=22
如下是错的:
http://baidu.com/ABC
http://baidu.com/abc/
http://baidu.com/abcde

nginx location指令详解_html

 

4、~* 表示:指定的正则表达式不区分大小写

nginx location指令详解_html

server {
server_name baidu.com;
location ~* ^/abc$ {
    ……
  }
}
那么,如下是对的:
http://baidu.com/abc
http://baidu..com/ABC
http://baidu..com/abc?p1=11&p2=22
如下是错的:
http://baidu..com/abc/
http://baidu..com/abcde

nginx location指令详解_html

 

5、^~ 类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,
那么就停止搜索其他模式了。
6、@ :定义命名location区段,这些区段客户段不能访问,只可以由内部产生的请
求来访问,如try_files或error_page等

查找顺序和优先级
1:带有“=“的精确匹配优先
2:没有修饰符的精确匹配
3:正则表达式按照他们在配置文件中定义的顺序
4:带有“^~”修饰符的,开头匹配
5:带有“~” 或“~*” 修饰符的,如果正则表达式与URI匹配
6:没有修饰符的,如果指定字符串与URI开头匹配

nginx location指令详解_html

Location区段匹配示例

location = / {
  # 只匹配 / 的查询.
  [ configuration A ]
}
location / {
  # 匹配任何以 / 开始的查询,但是正则表达式与一些较长的字符串将被首先匹配。
  [ configuration B ]
}
location ^~ /images/ {
  # 匹配任何以 /images/ 开始的查询并且停止搜索,不检查正则表达式。
  [ configuration C ]
}
location ~* \.(gif|jpg|jpeg)$ {
  # 匹配任何以gif, jpg, or jpeg结尾的文件,但是所有 /images/ 目录的请求将在Configuration C中处
  理。
  [ configuration D ]
} 各
请求的处理如下例:
■/ → configuration A
■/documents/document.html → configuration B
■/images/1.gif → configuration C
■/documents/1.jpg → configuration D

nginx location指令详解_html

 

root 、alias指令区别

location /img/ {
alias /var/www/image/;
}
#若按照上述配置的话,则访问/img/目录里面的文件时,ningx会自动去/var/www/image/目录找文件
location /img/ {
root /var/www/image;
}
#若按照这种配置的话,则访问/img/目录下的文件时,nginx会去/var/www/image/img/目录下找文件。]

alias是一个目录别名的定义,root则是最上层目录的定义。

还有一个重要的区别是alias后面必须要用“/”结束,否则会找不到文件的。。。而root则可有可无~~


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
0GY0ciDQP24T
最新推荐 更多