Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nginx Location匹配 #49

Open
varHarrie opened this issue Dec 5, 2022 · 0 comments
Open

Nginx Location匹配 #49

varHarrie opened this issue Dec 5, 2022 · 0 comments
Labels
Milestone

Comments

@varHarrie
Copy link
Owner

一、语法:

location [=|~|~*|^~] /uri/ { … }

二、修饰符:

修饰符 类型 说明 示例
= 普通匹配 精确匹配 location = /url/
^~ 普通匹配 普通字符串前缀匹配,忽略后续正则匹配 location ^~ /url/
普通匹配 普通字符串前缀匹配 location /url/
~ 正则匹配 正则匹配,区分大小写 location ~ .*.(js
~* 正则匹配 正则匹配,忽略大小写 location ~* .*.(js

三、顺序(先查找最长普通匹配,再顺序进行正则匹配):

image

1、找到精确匹配(=),不再往下查找

2、找到最长普通匹配,没有前缀(^~),往下顺序查找正则匹配

(1)找到符合的正则匹配,不再查找

(2)没有符合的正则匹配,使用最长普通匹配

3、找到最长普通匹配,有前缀(^~),不再往下查找

4、顺序查找正则匹配

四、示例

在线测试:https://nginx.viraptor.info/

1、

server {
 listen       80;
 server_name  test.com www.test.com;

 # A
 location ^~ /static/ {}

 # B
 location /static/js {}

 # C
 location ~* /(static|public)/ {}

 # D
 location = / {}
}

http://test.com/ -> D
http://test.com/static -> A
http://test.com/static/js -> C
这里B永远匹配不上,因为能匹配B的情况下,也都能匹配C

2、

server {
 listen       80;
 server_name  test.com www.test.com;

 # A
 location = / { }

 # B
 location / { }

 # C
 location /user/ { }

 # D
 location ^~ /images/ { }

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

http://test.com/index.html -> B
http://test.com/documents/about.html -> B
http://test.com/user/index.html -> C
http://test.com/user/abc.jpg -> E
http://test.com/images/abc.jpg -> D
http://test.com/ -> A

@varHarrie varHarrie added this to the Posts milestone Dec 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant