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 @ 2019-12-19 17:26  yifanSJ  阅读(965)  评论(0编辑  收藏  举报