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;
    }
}
复制代码
posted @   yifanSJ  阅读(999)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示