nginx路由匹配规则
一、root和alias的区别
root
实际访问文件路径会拼接URL中的路径
location ^~ /test/ {
root /usr/local/nginx/html/;
}
请求路径: http://192.168.60.128/test/test1.html
实际访问文件: /usr/local/nginx/html/test/test1.html
alias
实际访问文件路径不会拼接URL中的路径
location ^~ /test/ {
alias /usr/local/nginx/html/;
}
请求路径:http://192.168.60.128/test/test1.html
实际访问文件:/usr/local/nginx/html/test1.html (实际路径中没有test)
二、location指令的语法
其语法规则如下 location [=||*|^~] /uri/ { … }
= 用于不含正则表达式的 uri 前,要求请求字符串与 uri 严格匹配,如果匹配成功,就停止继续向下搜索并立即处理该请求
1.一般匹配
location /test/{
root /usr/local/nginx/html/;
index index.html index.htm;
}
2.精确匹配
location =/test/{
root /usr/local/nginx/html;
index index.html index.htm;
}
当一般匹配和严格匹配都能匹配到结果的时候,以严格匹配为准
~ 用于表示 uri 包含正则表达式,并且区分大小写
~* 用于表示 uri 包含正则表达式,并且不区分大小写
^~ 用于不含正则表达式的 uri 前,要求 Nginx 服务器找到标识 uri 和请求字符串匹配度最高的 location 后,立即使用此 location 处理请求,而不再使用 location 块中的正则 uri 和请求字符串做匹配
location ~ /test/ {
alias /usr/local/nginx/html/;
}
location ^~ /test/ {
root /usr/local/nginx/html/;
}
请求路径:/test/test1.html 实际访问^~ /test/