在 Nginx 中,location
块的优先级决定了当多个 location
匹配同一个请求时,哪个 location
块会被使用。Nginx 的 location
匹配规则如下:
- 精确匹配 (
=
): 完全匹配 URL 路径。 - 前缀匹配 (无修饰符): 匹配 URL 路径的前缀。
- 正则表达式匹配 (
~
或~*
): 使用正则表达式进行匹配,~
是区分大小写的,~*
是不区分大小写的。
如果需要使用 alias
指令来指定一个目录,通常是在前缀匹配中使用。alias
指令用于将请求映射到不同的文件系统路径。
下面是一个示例配置,展示了如何使用 alias
并解释了 location
的优先级:
server {
listen 80;
server_name example.com;
# 精确匹配 /exact 路径
location = /exact {
return 200 "Exact match for /exact\n";
}
# 正则表达式匹配 /regex 路径(区分大小写)
location ~ ^/regex$ {
return 200 "Regex match for /regex\n";
}
# 正则表达式匹配 /regex_case_insensitive 路径(不区分大小写)
location ~* ^/regex_case_insensitive$ {
return 200 "Regex case insensitive match for /regex_case_insensitive\n";
}
# 前缀匹配 /prefix 路径,并使用 alias 指令
location /prefix {
alias /var/www/prefix/;
try_files $uri $uri/ =404;
}
# 默认前缀匹配
location / {
root /var/www/html;
index index.html index.htm;
}
}
解释
- 精确匹配:
1location = /exact { 2 return 200 "Exact match for /exact\n"; 3}
这个
location
块只会匹配/exact
请求。 - 正则表达式匹配:
1location ~ ^/regex$ { 2 return 200 "Regex match for /regex\n"; 3}
这个
location
块会匹配/regex
请求,且区分大小写。 - 正则表达式匹配(不区分大小写):
1location ~* ^/regex_case_insensitive$ { 2 return 200 "Regex case insensitive match for /regex_case_insensitive\n"; 3}
这个
location
块会匹配/regex_case_insensitive
请求,且不区分大小写。 - 前缀匹配并使用
alias
:1location /prefix { 2 alias /var/www/prefix/; 3 try_files $uri $uri/ =404; 4}
这个
location
块会匹配以/prefix
开头的所有请求,并将这些请求映射到/var/www/prefix/
目录下的文件。 - 默认前缀匹配:
1location / { 2 root /var/www/html; 3 index index.html index.htm; 4}
如果没有其他
location
块匹配,则使用这个默认的location
块。
通过这种方式,你可以控制不同类型的请求被路由到不同的处理逻辑或文件系统路径。