Nginx location匹配规则

栏目: 服务器 · Nginx · 发布时间: 4年前

内容简介:以下列配置为例

以下列配置为例

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、必选规则

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叔区块链」 - 专注于区块链技术学习

Nginx location匹配规则

博客地址: http://www.jouypub.com

简书主页: https://www.jianshu.com/u/756c9c8ae984

segmentfault主页: https://segmentfault.com/blog/jouypub

腾讯云主页: https://cloud.tencent.com/developer/column/72548

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Complexity and Approximation

Complexity and Approximation

G. Ausiello、P. Crescenzi、V. Kann、Marchetti-sp、Giorgio Gambosi、Alberto M. Spaccamela / Springer / 2003-02 / USD 74.95

This book is an up-to-date documentation of the state of the art in combinatorial optimization, presenting approximate solutions of virtually all relevant classes of NP-hard optimization problems. The......一起来看看 《Complexity and Approximation》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具