美文网首页jouypub.com
Nginx location匹配规则

Nginx location匹配规则

作者: JouyPub | 来源:发表于2019-07-02 13:38 被阅读0次

以下列配置为例

server {
    listen       80;
    server_name  jouypub.com;

    location ^~ /. {
        return 404;
    }
    location ^~ /api {
        proxy_pass http://localhost:8000;
    }
    location / {
        root /services/apps/front/;
    }
}

location语法规则: location [=|~|~*|^~] /uri/ { … }

= 开头表示精确匹配
^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可
~ 表示区分大小写的正则匹配
~* 表示不区分大小写的正则匹配
!~!~* 分别为区分大小写不匹配及不区分大小写不匹配 的正则
/ 通用匹配,任何请求都会匹配到。

如果匹配规则以^开头,就是匹配以指定字符串开头的路径,如果没有就是匹配url中的内容是否包含指定字符串
如果匹配规则以$结尾,就是匹配以指定字符串结尾的路径

多个location配置的情况下匹配顺序为(当有匹配成功时候,停止匹配,按当前匹配规则处理请求):

  1. 优先匹配 =
  2. 其次匹配 ^~
  3. 按照文件中的匹配顺序执行
  4. 最后匹配 /

举例

1、必选规则

location / {
    root /services/apps/front/;
}

2、匹配静态资源

location ^~ /static/ {
    root /services/apps/front/static;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
    root /webroot/res/;
}

3、防盗链

location ~* \.(gif|jpg|swf)$ {
    valid_referers none blocked jouypub.com files.jouypub.com;
    if ($invalid_referer) {
        rewrite ^/ http://$host/logo.png;
    }
}

jouypub.com、files.jouypub.com是运行出现的白名单

4、根据文件类型设置过期时间

location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
    if (-f $request_filename) {
        expires 1h;
        break;
    }
}

5、禁止访问某个目录

location ~* \.(txt|doc)${
    root /services/apps/front/doc;
    deny all;
}

location中的/结尾和非/结尾

location ^~ /api {
    proxy_pass http://localhost:8000;
}
location ^~ /api {
    proxy_pass http://localhost:8000/;
}

访问路径http://www.jouypub.com/api/a.html
规则1会被转发到:http://localhost:8000/api/a.html
规则2会被转发到:http://localhost:8000/a.html

欢迎订阅「K叔区块链」 - 专注于区块链技术学习
博客地址:http://www.jouypub.com
简书主页:https://www.jianshu.com/u/756c9c8ae984
segmentfault主页:https://segmentfault.com/blog/jouypub
腾讯云主页:https://cloud.tencent.com/developer/column/72548

相关文章

网友评论

    本文标题:Nginx location匹配规则

    本文链接:https://www.haomeiwen.com/subject/mcyzcctx.html