nginx
主页 > 服务器 > nginx >

Nginx location(正则)使用介绍

2024-06-22 | 佚名 | 点击:

1、nginx location

location 指令的作用是根据用户请求的URI来执行不同的应用。

location使用的语法

1

2

3

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

  ······

}

解释:

location [=||*|^~] uri {…}
指令 匹配标识 匹配的网站地址 匹配URI后要执行的配置段

2、匹配标识说明

3、不同uri及特殊字符组合匹配的顺序说明

顺序 不用URI及特殊字符组合匹配 匹配说明
1 location = / {} 精确匹配 /
2 location ^~ /image/{ 匹配常规字符串,不做正则表达式匹配检查
3 location ~* \.(gif|jpg|jpeg)$ { 正则匹配
4 location /documents/ { 匹配常规字符串,如果有正则,则优先匹配正则
5 location / { 所有location 都不能匹配后的默认匹配

4、示例

测试代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

#location / {

#    root   html;

#    autoindex on;

#    index  index.html index.htm;

#}

 

location / {

        return 401;

}

location = / {

        return 402;

}

location /documents/ {

        return 403;

}

location ^~ /images/ {

        return 404;

}

location ~* \.(gif|jpg|jpeg)$ {

        return 500;

}

访问测试

1

2

3

4

5

6

7

8

9

10

[root@www conf]# curl -I -w "%{http_code}\n" -o /dev/null -s 192.168.150.12/docuements

401

[root@www conf]# curl -I -w "%{http_code}\n" -o /dev/null -s 192.168.150.12

402

[root@www conf]# curl -I -w "%{http_code}\n" -o /dev/null -s http://192.168.150.12/documents/

403

[root@www conf]# curl -I -w "%{http_code}\n" -o /dev/null -s 192.168.150.12/images/a.jpg

404

[root@www conf]# curl -I -w "%{http_code}\n" -o /dev/null -s 192.168.150.12/docuements/abc.jpg

500

原文链接:
相关文章
最新更新