一、location
Nginx的HTTP配置主
http { ###协议
include mime.types;
default_type application/octet-stream;
keepalive_timeout 65;
gzip on;
server { ###服务器
listen 80;
server_name localhost;
location / { ###请求
root html;
index index.html index.htm;
}
}
}
二、各个区段的含义
1."=“表示精确匹配(例如输入”/data/a"只会匹配到"/data/a")
2."^~“表示一字符串开头进行匹配
3.”~ “开头表示区分大小写的正则匹配
4.”~*" 开头表示不区分大小写的正则匹配
5"/ -"通用匹配(模糊匹配)
三、匹配顺序
1.只要匹配到,进程便会终止,因此在写location的时候一定要注意顺序,因为匹配过程中是按照顺序执行
2.一般精确匹配在首位,通用匹配在最后,区分大小写在不区分大小写之前
四、下面的代码可以更好地理解(可以打开两个终端,分别打开错误日志和登入日志,可以更直观的看出变化)
import re
def fregxeq():
return "this is my ="
def fregxw():
return "this is my /"
def fregxd():
return "this is my ~*"
def fregxD():
return "this is my ~"
def fregxh():
return "this is my ^"
#代表nginx中的等于,精确匹配
regxeq = re.compile("/abc/index.html")
#代表nginx中的/
regxw = re.compile("/.*")
#代表nginx中的~,大小写敏感的正则表达式,输入的path不进行大小写转换
regxD = re.compile(".*\.(jpg|png)$")
#代表nginx中的~*,忽略大小写,输入的path路径要转换为小写后进行正则匹配
regxd = re.compile(".*\.(jpg|png)$")
#代表以什么开头的正则表达式
regxh = re.compile("^/images.*")
#一般精确匹配在首位,通用匹配在最后,区分大小写在不区分大小写之前
d = {regxeq:fregxeq,regxD:fregxD,regxd:fregxd,regxh:fregxh,regxw:fregxw}
path = "/images/abc/index.html"
for regx in d:
try:
if regx.match(path).group():
print(d[regx]())
break
except Exception as f:
print(f)
location中加入的部署
#精确的正则表达式注册
location = /abc/index.html {
root /data/eq;
index index.html;
}
#区分大小写的正则表达式注册
location ~ \.(gif|jpg|jpeg)$ {
root /data/ignoreuperlower;
index index.jpg;
}
#不区分大小写的正则表达式注册
location ~* \.(gif|jpg|jpeg)$ {
root /data/d;
index index.jpg;
}
#注册正则表达式以什么开头的path
location ^~ /images.* {
root /data/images;
index index.jpg;
}
#匹配任意所有的正则表达式
location / {
root /usr/share/nginx/html;
index index.html index.htm;