关于Nginx的一些常用配置及含义

175 阅读2分钟

location 修饰语符号解释

  • = 开头表示精确匹配
  • ^~ 开头表示匹配url路径即可
  • ~ 区分大小写的正则匹配
  • ~*不区分大小写的正则匹配
  • /通配符

简单例子

######
# *********** 无修饰语 匹配项只能是字符串,不能是正则 ****************
######

# / 表示通用匹配:
location  / {}
# /index.html ok

location  /test {}
# /test ok
# /test2 ok
# /test/ ok

######
# *********** 有修饰语 ****************
######

# = 表示精确匹配,完全匹配URI中除访问参数意外内容:
location  = /test {}
# /test ok
# /test/ not ok
# /test2 not ok
# /test/2 not ok 

# ~ 表示区分大小写的正则匹配,比如:
location  ~ ^/test$ {}
# /test ok
# /Test not ok
# /test/ not ok
# /test2 not ok


# ~* 表示不区分大小写的正则匹配
location  ~* ^/test$ {}
# /test ok
# /Test ok
# /test/ not ok
# /test2 not ok


# ^~ 表示 uri 以某个字符串开头
location ^~ /images/ {}
# /images/1.gif ok

匹配顺序

当存在多个 location 的时候,

在顺序上,前缀字符串顺序不重要,按照匹配长度来确定,正则表达式则按照定义顺序。

在优先级上,= 修饰符最高,^~ 次之,再者是正则,最后是前缀字符串匹配。

server {    
    location /doc {        [ configuration A ]     }    
    location /docu {        [ configuration B ]     }
}
# 请求 /document 使用 configuration B
# 虽然 /doc 也能匹配到,但在顺序上,前缀字符串顺序不重要,按照匹配长度来确定
server {    
    location ~ ^/doc {        [ configuration A ]     }    
    location ~ ^/docu {        [ configuration B ]     }
}
# 请求 /document 使用 configuration A
# 虽然 ~ ^/docu 也能匹配到,但正则表达式则按照定义顺序
server {    
    location ^~ /doc {        [ configuration A ]     }    
    location ~ ^/docu {        [ configuration B ]     }
}
# 请求 /document 使用 configuration A
# 虽然 ~ ^/docu 也能匹配到,但 ^~ 的优先级更高
server {    
    location /document {        [ configuration A ]     }    
    location ~ ^/docu {        [ configuration B ]     }
}
# 请求 /document 使用 configuration B
# 虽然 /document 也能匹配到,但正则的优先级更高

http server 配置

http {
    server {
        server_name example.com .example.com; # 泛域名
        server_name www.example.; # 多个后缀域名
        server_name ~^ (www\.)?(.+)$;
    }
}

代理

正向代理

正向代理是客户端设置代理地址后,通过将代理服务器IP作为源IP访问互联网应用服务的代理方式。

反向代理

反向代理是用户客户端访问代理服务器后,被反向代理服务器软件按照一定规则从一个或多个被代理服务器中获取响应资源并返回给客户端的代理模式。