nginx-location配置块

location 配置块

其中 location 用于匹配请求的 URI。

URI 表示的是访问路径,除域名和协议以外的内容,比如说我访问了https://www.shiyanlou.com/louplus/linux,https:// 是协议,www.shiyanlou.com 是域名,/louplus/linux 是 URI。

location 匹配的方式有多种:

  • 精准匹配

  • 忽略大小写的正则匹配

  • 大小写敏感的正则匹配

  • 前半部分匹配

其语法如下:

location [ = | ~ | ~* | ^~ ] pattern {
#    ......
#    ......
}

其中各个符号的含义:

  • =:用于精准匹配,想请求的 URI 与 pattern 表达式完全匹配的时候才会执行 location 中的操作

  • ~:用于区分大小写的正则匹配;

  • ~*:用于不区分大小写的正则匹配;

  • ^~:用于匹配 URI 的前半部分;

我们以这样的实例来进一步理解:

# 当访问 www.xxx.com 时,请求访问的是 /,所以将与配置 A 匹配;
location = / {
    # [ 配置 A ]
}
# 当访问 www.xxx.com/test.html 时,请求将与配置 B 匹配;
location / {
    # [ 配置 B ]
}
# 当访问 www.xxx.com/documents/document.html 时,请求将匹配配置 C
location /documents/ {
    # [ 配置 C ]
}
# 当访问 www.xxx.com/images/1.gif 请求将匹配配置 D;
location ^~ /images/ {
    # [ 配置 D ]
}
# 当访问 www.xxx.com/docs/1.jpg 请求将匹配配置 E。
location ~* .(gif|jpg|jpeg)$ {
    # [ 配置 E ]
}

当一个 URI 能够同时配被多 location 匹配的时候,则按顺序被第一个 location 所匹配。

在 location 中处理请求的方式有很多,如上文中的 try_files $uri $uri/ =404;,它是一种特别常用的写法。

我们来分析一下 try_files $uri $uri/ =404;。这里假设我定义的 root 为/usr/share/nginx/html/,访问的 URI 是 /hello/shiyanlou。

# 虚拟主机的配置
server {
    # 侦听 80 端口,分别配置了 IPv4 和 IPv6
    listen 80 default_server;
    listen[::]:80 default_server ipv6only=on;

    # 定义服务器的默认网站根目录位置
    root /usr/share/nginx/html;

    # 定义主页的文件名
    index index.html index.htm;

    # 定义虚拟服务器的名称
    server_name localhost;
    
    # location 块
    location / {
        try_files $uri $uri/ =404;
    }
}
  • 第一步:当 URI 被匹配后,会先查找/usr/share/nginx/html//hello/shiyanlou 这个文件是否存在,如果存在则返回,不存在进入下一步。

  • 第二步:查找 /usr/share/nginx/html//hello/shiyanlou/ 目录是否存在,如果存在,按 index 指定的文件名进行查找,比如 index.html,如果存在则返回,不存在就进入下一步。

  • 第三步:返回 404 Not Found。

原文地址:https://www.cnblogs.com/Paul-watermelon/p/14248486.html