Nginx location指令

location是Nginx配置文件中的一个指令,用于根据用户请求的网站地址URL进行匹配,匹配成功即进行相关操作。
默认nginx配置文件中至少存在一个location。

语法

location [ = | ~ | ~* | ^~ ] uri {
   ...
}

说明:
= 精确匹配,优先级最高,属于普通字符串匹配。
^~ 匹配以什么开头,如果匹配到了不再进行正则表达式匹配,属于普通字符串匹配。
~ 区分大小写匹配,属于正则表达式匹配。
~* 不区分大小写匹配,属于正则表达式匹配。
! 可使用逻辑操作符!进行匹配取反操作,如!~!~*


案例

配置文件如下

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;
        default_type text/html;
		root html;

        location / {
            return 401;
        }

        location = / {
            return 402;
        }
		
        location /documents/ {
            return 403;
        }
	#匹配前缀以/images开头的请求
        location ^~ /images/ {
            return 404;
        }
	#匹配任何以gif、jpg或jepg结尾的请求
        location ~* \.(gif|jpg|jpeg)$ {
            return 500;
        }		

    }

访问结果

请求url 返回结果
http://10.154.0.111 402
http://10.154.0.111/index.html 402
http://10.154.0.111/documents/document.html 401
http://10.154.0.111/images/1.gif 404
http://10.154.0.111/documents/1.jpg 500
http://10.154.0.111/tz/ 401
http://10.154.0.111/aasdf 401

/images/1.gif匹配到了404,不再进行正则表达式匹配,所以不会返回500

匹配优先级

= > ^~ > ~* > /documents/ > /
精确匹配 > 前缀匹配 > 正则匹配 > 字符串匹配 > 默认匹配/


学习来自:跟老男孩学Linux运维 Web集群实战 第五章

posted @ 2021-01-12 18:21  努力吧阿团  阅读(185)  评论(0)    收藏  举报