Nignx(四)location语法详解
1. Location语法优先级排列
匹配符 匹配规则 优先级 = 精确匹配 1 ^~ 以某个字符串开头 2 ~ 区分大小写的正则匹配 3 ~* 不区分大小写的正则匹配 4 !~ 区分大小写不匹配的正则 5 !~* 不区分大小写不匹配的正则 6 / 通用匹配,任何请求都会匹配到 7
(location =) > (location 完整路径) > (location ^~ 路径) > (location ~,~* 正则顺序) > (location 部分起始路径) > (/)
2. nginx.conf配置文件实例
server { listen 80; server_name pythonav.cn; #优先级1,精确匹配,根路径 location =/ { return 400; } #优先级2,以某个字符串开头,以av开头的,优先匹配这里,区分大小写 location ^~ /av { root /data/av/; } #优先级3,区分大小写的正则匹配,匹配/media*****路径 location ~ /media { alias /data/static/; } #优先级4 ,不区分大小写的正则匹配,所有的****.jpg|gif|png 都走这里 location ~* .*\.(jpg|gif|png|js|css)$ { root /data/av/; } #优先7,通用匹配 location / { return 403; } }
3. nginx语法之root和alias区别实战
注意:本地测试前提前配置SwitchHosts,映射tests.com为本地IP
server {
listen 80;
server_name tests.com;
# http://tests.com/ccc.png => D:\test\ccc.png
# http://http://tests.com/index3.html => D:\test\index3.html
# http://tests.com/tupian/bb.png => D:\test\tupian\bb.png
location ~\.(html|js|css|png|gif|icon|jpg|ttf|woff|woff2|properties|eot|svg|php|ico|map|swf|asp|php|aspx|jsp|do|action|shtml|htm|txt|apk|json)$ {
root D://test;
index index.html;
}
# http://tests.com/tupian/bb.png => D:\test\tupian\bb.png
location ^~ /tupian {
root D://test;
}
# http://tests.com/yemian/ => D:\test\yemian\index.html
location /yemian {
root D://test;
index index.html;
}
# http://tests.com/aliasym/index2.html => D:\test\index2.html
location ^~ /aliasym {
alias D://test;
}
# http://tests.com/ => D:\test\index2.html
location / {
root D://test;
index index2.html;
}
# http://tests.com/ => D:\test\index.html
location =/ {
rewrite / /index.html break;
root D://test;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了