Nginx-Location 配置详解

2022/4/2 nginx

# 语法

Location 块通过指定模式来与客户端请求的URI相匹配。

Location基本语法:

匹配uri类型,有四种参数可选,也可以不带参数。

命名location,用@来标识,类似于定义goto语句块。 ··· location [ = | ~ | ~* | ^~ ] /uri/ { … } location @/name/ { … } ···

参数 解释
    空 location后没有参数直接跟着URI,表示前缀匹配,代表跟请求中的URI从头开始匹配。
= 用于标准 uri 前,要求请求字符串与其严格匹配,成功则立即处理,nginx停止搜索其他匹配。
^~ 用于标准 uri 前,并要求一旦匹配到就会立即处理,不再去匹配其他的那些个正则 uri,一般用来匹配目录
~ 用于正则 uri 前,表示 uri 包含正则表达式, 区分大小写
~* 用于正则 uri 前, 表示 uri 包含正则表达式, 不区分大小写
@ "@" 定义一个命名的 location,@定义的locaiton名字一般用在内部定向,例如error_page, try_files命令中。它的功能类似于编程中的goto。

# 示例

server {
    listen      80;
    server_name www.2u1.com;
 
    # 情形A
    # 访问 http://www.2u1.com/testa/aaaa
    # 后端的request_uri为: /testa/aaaa
    location ^~ /testa/ {
        proxy_pass http://127.0.0.1:8801;
    }
    
    # 情形B
    # 访问 http://www.2u1.com/testb/bbbb
    # 后端的request_uri为: /bbbb
    location ^~ /testb/ {
        proxy_pass http://127.0.0.1:8801/;
    }
 
    # 情形C
    # 下面这段location是正确的
    location ~ /testc {
        proxy_pass http://127.0.0.1:8801;
    }
 
    # 情形D
    # 下面这段location是错误的
    #
    # nginx -t 时,会报如下错误: 
    #
    # nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular 
    # expression, or inside named location, or inside "if" statement, or inside 
    # "limit_except" block in /opt/app/nginx/conf/vhost/test.conf:17
    # 
    # 当location为正则表达式时,proxy_pass 不能包含URI部分。本例中包含了"/"
    location ~ /testd {
        proxy_pass http://127.0.0.1:8801/;   # 记住,location为正则表达式时,不能这样写!!!
    }
 
    # 情形E
    # 访问 http://www.2u1.com/ccc/bbbb
    # 后端的request_uri为: /aaa/ccc/bbbb
    location /ccc/ {
        proxy_pass http://127.0.0.1:8801/aaa$request_uri;
    }
 
    # 情形F
    # 访问 http://www.2u1.com/namea/ddd
    # 后端的request_uri为: /yongfu?namea=ddd
    location /namea/ {
        rewrite    /namea/([^/]+) /yongfu?namea=$1 break;
        proxy_pass http://127.0.0.1:8801;
    }
 
    # 情形G
    # 访问 http://www.2u1.com/nameb/eee
    # 后端的request_uri为: /yongfu?nameb=eee
    location /nameb/ {
        rewrite    /nameb/([^/]+) /yongfu?nameb=$1 break;
        proxy_pass http://127.0.0.1:8801/;
    }
 
    access_log /data/logs/test.log;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64