前端nginx常用知识

764 阅读2分钟

1、location语法规则

location [= | ^~ | ~ | ~* ] /uri/{
    # ...
}
// 定义nginx内部服务跳转
location @name {
    
}

2、location语法详解

规则匹配优先级别正则含义
location = /uri1= 表示精确匹配,只有完全匹配上才能生效
location ^~ /uri2^~ 开头对 URL 路径进行前缀匹配,并且在正则之前
location ~ /uri3开头表示区分大小写的正则匹配前
location ~* /uri4开头表示不区分大小写的正则匹配
location /uri5不带任何修饰符,也表示前缀匹配,但是在正则匹配之后
location /6通用匹配,任何未匹配到其它 location 的请求都会匹配到,相当于 switch 中的 default

注意: 匹配优先级别从小到大,与 location 配置顺序无关

3、location匹配解析

3.1、root解析

解析过程

  1. location 和 root拼接处理
  2. 拼接后的 “//” 合并成 “/”

解析示例

locationroot解析结果
/homehtml/a/bhtml/a/b/home/index.html
/home/html/a/bhtml/a/b/home/index.html
/homehtml/a/b/html/a/b/home/index.html
/home/html/a/b/html/a/b/home/index.html

3.2、别名alias解析

解析过程

  1. alias替换访问地址中location匹配的部分

解析示例

locationalias解析结果
/homehtml/a/b/html/a/b/index.html
/home/html/a/b/html/a/b/index.html
/homehtml/a/b//html/a/b//index.html
/home/html/a/b//html/a/b/index.html

3.3、代理proxy_pass解析

解析过程

  1. 如果代理地址端口后不存在路径,则替换原访问地址location之前的部分
  2. 如果代理地址端口后存在路径,则(和alias解析一样)替换location匹配部分及之前的部分

解析示例

locationproxy_pass解析结果
/homehttp://localhost:8080/home/index.html
/home/http://localhost:8080/home/index.html
/homehttp://localhost:8080///index.html
/home/http://localhost:8080//index.html
/homehttp://localhost:8080/proxy_home/proxy_home/index.html
/home/http://localhost:8080/proxy_home/proxy_homeindex.html
/homehttp://localhost:8080/proxy_home//proxy_home//index.html
/home/http://localhost:8080/proxy_home//proxy_home/index.html

3.4、@name解析

定义nginx内部服务跳转,可以简单理解为一个location处理function调用。

location / {
    root /wwwroot;
    try_files index.html index.htm @welcome;
}

# welcome
location @welcome{
    root /wwwroot/welcome;
    index index.html index.htm;
}